使用ctypes在python中创建背景转换器,而不是工作

时间:2014-02-12 00:04:23

标签: python ctypes

我正在制作一个简单的(我认为)程序,为一周中的每一天设置不同的桌面背景。它运行没有错误但没有任何反应。图像的路径有效。有什么想法吗?

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)

3 个答案:

答案 0 :(得分:2)

我必须阅读有关此主题的所有现有网站,并在放弃之前,来到这个工作代码(win7 pro 64 bit,python 3.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)




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

答案 1 :(得分:1)

这不是您问题的答案,但您通常可以通过执行以下操作来缩小程序并删除冗余:

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)

答案 2 :(得分:1)

如果您使用的是Python 3,则应使用ctypes.windll.user32.SystemParametersInfoW代替ctypes.windll.user32.SystemParametersInfoA(W而不是A,this answer表示)。 Another answer描述了这一点,因为在Python 3中,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)
不要重复自己。