如何在 python 中设置桌面背景? (windows)
How do I set the desktop background in python? (windows)
这就是我正在尝试的:
import ctypes
import os
drive = "F:\"
folder = "Keith's Stuff"
image = "midi turmes.png"
image_path = os.path.join(drive, folder, image)
SPI_SETDESKWALLPAPER = 20
ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, image_path, 3)
基本上,这段代码显然应该将桌面背景设置为 midi turmes.png,它改变了桌面,但是,出于某种奇怪的原因,它始终是绿色背景(我在 windows 是图像后面的绿色背景)如何解决这个问题并使桌面看起来像这样?:http://i.imgur.com/VqMZF6H.png
以下适合我。我正在使用 Windows 10 64 位和 Python 3.
import os
import ctypes
from ctypes import wintypes
drive = "c:\"
folder = "test"
image = "midi turmes.png"
image_path = os.path.join(drive, folder, image)
SPI_SETDESKWALLPAPER = 0x0014
SPIF_UPDATEINIFILE = 0x0001
SPIF_SENDWININICHANGE = 0x0002
user32 = ctypes.WinDLL('user32')
SystemParametersInfo = user32.SystemParametersInfoW
SystemParametersInfo.argtypes = ctypes.c_uint,ctypes.c_uint,ctypes.c_void_p,ctypes.c_uint
SystemParametersInfo.restype = wintypes.BOOL
print(SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, image_path, SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE))
重要的是,如果使用 SystemParametersInfoW
,请确保为 image_path
使用 Unicode 字符串,如果使用 SystemParametersInfoA
,则确保使用字节字符串。请记住,在 Python 中,3 个字符串是默认的 Unicode。
同时设置 argtypes
和 restype
也是一个好习惯。您甚至可以 "lie" 并将第三个 argtypes 参数设置为 c_wchar_p
for SystemParametersInfoW
然后 ctypes 将验证您传递的是 Unicode 字符串而不是字节字符串。
这就是我正在尝试的:
import ctypes
import os
drive = "F:\"
folder = "Keith's Stuff"
image = "midi turmes.png"
image_path = os.path.join(drive, folder, image)
SPI_SETDESKWALLPAPER = 20
ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, image_path, 3)
基本上,这段代码显然应该将桌面背景设置为 midi turmes.png,它改变了桌面,但是,出于某种奇怪的原因,它始终是绿色背景(我在 windows 是图像后面的绿色背景)如何解决这个问题并使桌面看起来像这样?:http://i.imgur.com/VqMZF6H.png
以下适合我。我正在使用 Windows 10 64 位和 Python 3.
import os
import ctypes
from ctypes import wintypes
drive = "c:\"
folder = "test"
image = "midi turmes.png"
image_path = os.path.join(drive, folder, image)
SPI_SETDESKWALLPAPER = 0x0014
SPIF_UPDATEINIFILE = 0x0001
SPIF_SENDWININICHANGE = 0x0002
user32 = ctypes.WinDLL('user32')
SystemParametersInfo = user32.SystemParametersInfoW
SystemParametersInfo.argtypes = ctypes.c_uint,ctypes.c_uint,ctypes.c_void_p,ctypes.c_uint
SystemParametersInfo.restype = wintypes.BOOL
print(SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, image_path, SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE))
重要的是,如果使用 SystemParametersInfoW
,请确保为 image_path
使用 Unicode 字符串,如果使用 SystemParametersInfoA
,则确保使用字节字符串。请记住,在 Python 中,3 个字符串是默认的 Unicode。
同时设置 argtypes
和 restype
也是一个好习惯。您甚至可以 "lie" 并将第三个 argtypes 参数设置为 c_wchar_p
for SystemParametersInfoW
然后 ctypes 将验证您传递的是 Unicode 字符串而不是字节字符串。