用ctypes在python中创建一个背景转换器,不起作用

2024-05-15 21:48:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个简单的(我想)程序来为一周中的每一天设置不同的桌面背景。它运行时没有错误,但什么也没有发生。图像的路径有效。有什么想法吗?在

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:\Users\Owner\Documents\Wallpaper\1.jpg",0)

elif wkd == 0:
    ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER,0,r"C:\Users\Owner\Documents\Wallpaper\2.jpg",0)

elif wkd == 1:
    ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER,0,r"C:\Users\Owner\Documents\Wallpaper\3.jpg",0)

elif wkd == 2:
    ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER,0,r"C:\Users\Owner\Documents\Wallpaper\4.jpg",0)

elif wkd == 3:
    ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER,0,r"C:\Users\Owner\Documents\Wallpaper\5.jpg",0)

elif wkd == 4:
    ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER,0,r"C:\Users\Owner\Documents\Wallpaper\6.jpg",0)

elif wkd == 5:
    ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER,0,r"C:\Users\Owner\Documents\Wallpaper\7.jpg",0)

Tags: spitimectypesusersdocumentsjpgownerelif
3条回答

如果您使用的是python3,那么应该使用ctypes.windll.user32.SystemParametersInfoW而不是{}(W而不是{a1}所说的)。 Another answer描述了这一点,因为在python3中,str类型是UTF-16的形式,在C中是wchar_t *

另外,请将代码最小化,如下所示:

import time;
import ctypes;
SPI_SETDESKWALLPAPER = 20

wallpapers = r"C:\Users\Owner\Documents\Wallpaper\%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:\Users\Owner\Documents\Wallpaper\1.jpg",
    r"C:\Users\Owner\Documents\Wallpaper\2.jpg",
    r"C:\Users\Owner\Documents\Wallpaper\3.jpg",
    r"C:\Users\Owner\Documents\Wallpaper\4.jpg",
    r"C:\Users\Owner\Documents\Wallpaper\5.jpg",
    r"C:\Users\Owner\Documents\Wallpaper\6.jpg",
    r"C:\Users\Owner\Documents\Wallpaper\7.jpg",
]

localtime = time.localtime(time.time())
wkd = localtime[6]
ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, wallpapers[wkd], 0)

我一定读过所有关于这个主题的站点,在放弃之前,我找到了这个工作代码(win7pro64位,python3.4)

import ctypes SPI_SETDESKWALLPAPER = 0x14 #which command (20) SPIF_UPDATEINIFILE = 0x2 #forces instant update src = r"D:\Downloads\_wallpapers\3D-graphics_Line_025147_.jpg" #full file location #in python 3.4 you have to add 'r' before "path\img.jpg" print(ctypes.windll.user32.SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, src, SPIF_UPDATEINIFILE)) #SystemParametersInfoW instead of SystemParametersInfoA (W instead of A) ; 第13章; 第13章;

希望它能帮助你和其他许多似乎有类似问题的人。在

相关问题 更多 >