我正在开发一个简单的(我认为)程序,为一周中的每一天设置不同的桌面背景。它运行没有错误,但没有任何反应。图像的路径有效。有什么想法吗?
import time;
import ctypes;
SPI_SETDESKWALLPAPER = 20
localtime = time.localtime(time.time())
wkd = localtime[6]
if wkd == 6:
ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER,0,r"C:UsersOwnerDocumentsWallpaper1.jpg",0)
elif wkd == 0:
ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER,0,r"C:UsersOwnerDocumentsWallpaper2.jpg",0)
elif wkd == 1:
ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER,0,r"C:UsersOwnerDocumentsWallpaper3.jpg",0)
elif wkd == 2:
ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER,0,r"C:UsersOwnerDocumentsWallpaper4.jpg",0)
elif wkd == 3:
ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER,0,r"C:UsersOwnerDocumentsWallpaper5.jpg",0)
elif wkd == 4:
ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER,0,r"C:UsersOwnerDocumentsWallpaper6.jpg",0)
elif wkd == 5:
ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER,0,r"C:UsersOwnerDocumentsWallpaper7.jpg",0)
我一定已经阅读了有关此主题的每个现有站点,并且在放弃之前,来到了这个工作代码(win7 pro 64位,python 3.4)
import ctypes
SPI_SETDESKWALLPAPER = 0x14 #which command (20)
SPIF_UPDATEINIFILE = 0x2 #forces instant update
src = r"D:Downloads_wallpapers3D-graphics_Line_025147_.jpg" #full file location
#in python 3.4 you have to add 'r' before "pathimg.jpg"
print(ctypes.windll.user32.SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, src, SPIF_UPDATEINIFILE))
它使用 SystemParametersInfoW
而不是 SystemParametersInfoA
(W 而不是 A)。
希望它对您和许多其他似乎有类似问题的人有所帮助。
如果你使用的是Python 3,你应该使用ctypes.windll.user32.SystemParametersInfoW
而不是ctypes.windll.user32.SystemParametersInfoA
(W而不是A,正如这个答案所说)。另一个答案描述,因为在Python 3中,str
类型的形式是UTF-16,就像C中的wchar_t *
一样。
更重要的是,请像这样最小化代码:
import time;
import ctypes;
SPI_SETDESKWALLPAPER = 20
wallpapers = r"C:UsersOwnerDocumentsWallpaper%d.jpg"
localtime = time.localtime(time.time())
wkd = localtime[6]
ctypes.windll.user32.SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, wallpapers%(wkd+1), 0)
不要重复自己。
这不是您问题的答案,但您通常可以通过执行以下操作来缩小程序并删除冗余:
import time;
import ctypes;
SPI_SETDESKWALLPAPER = 20
wallpapers = [
r"C:UsersOwnerDocumentsWallpaper1.jpg",
r"C:UsersOwnerDocumentsWallpaper2.jpg",
r"C:UsersOwnerDocumentsWallpaper3.jpg",
r"C:UsersOwnerDocumentsWallpaper4.jpg",
r"C:UsersOwnerDocumentsWallpaper5.jpg",
r"C:UsersOwnerDocumentsWallpaper6.jpg",
r"C:UsersOwnerDocumentsWallpaper7.jpg",
]
localtime = time.localtime(time.time())
wkd = localtime[6]
ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, wallpapers[wkd], 0)
我发现了一个非常奇怪的原因,为什么我的代码不起作用。
我有这样的功能:
ctypes.windll.user32.SystemParametersInfoW(0x14, 0, """C:/Users/myUser/Desktop/
VSCoding/Python/TheWelcomer/test.jpg""", 0x2)
(路径之间有一个输入)
这不起作用,我只是得到了一个黑色的桌面背景
但是当我摆脱该输入时,如下所示:
ctypes.windll.user32.SystemParametersInfoW(0x14, 0, """C:/Users/myUser/Desktop/VSCoding/Python/TheWelcomer/test.jpg""", 0x2)
成功了