如何在python中设置桌面背景? (视窗) [英] 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
Basicaly, this code is obviously supposed to set the desktop background to midi turmes.png, it changes the desktop, however, for some odd reason, it's always a green background (my personalized settings in windows is a green background behind the image) how do I fix this and make the desktop look like this?: http://i.imgur.com/VqMZF6H.png
推荐答案
以下对我有用。我正在使用Windows 10 64位和Python 3。
The following works for me. I'm using Windows 10 64-bit and 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。
The important part is to make sure to use a Unicode string for image_path
if using SystemParametersInfoW
, and a byte string if using SystemParametersInfoA
. Remember that in Python 3 strings are default Unicode.
设置 argtypes
和<$ c也是一种好习惯$ c>重新输入。您甚至可以撒谎并将第三个argtypes参数设置为 SystemParametersInfoW
的 c_wchar_p
,然后ctypes将验证您是否传递Unicode字符串而不是字节字符串。
It is also good practice to set argtypes
and restype
as well. You can even "lie" and set the third argtypes parameter to c_wchar_p
for SystemParametersInfoW
and then ctypes will validate that you are passing a Unicode string and not a byte string.
这篇关于如何在python中设置桌面背景? (视窗)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!