问题
I've been trying to find the best way to change the Windows 10 Desktop wallpaper through a python script. When I try to run this script, the desktop background turns to a solid black color.
import ctypes
path = 'C:\\Users\\Patrick\\Desktop\\0200200220.jpg'
def changeBG(path):
SPI_SETDESKWALLPAPER = 20
ctypes.windll.user32.SystemParametersInfoA(20, 0, path, 3)
return;
changeBG(path)
What can I do to fix this? I'm using python3
回答1:
For 64 bit windows, use:
ctypes.windll.user32.SystemParametersInfoW
for 32 bit windows, use:
ctypes.windll.user32.SystemParametersInfoA
If you use the wrong one, you will get a black screen. You can find out which version your using in Control Panel -> System and Security -> System.
You could also make your script choose the correct one:
import struct
import ctypes
PATH = 'C:\\Users\\Patrick\\Desktop\\0200200220.jpg'
SPI_SETDESKWALLPAPER = 20
def is_64bit_windows():
"""Check if 64 bit Windows OS"""
return struct.calcsize('P') * 8 == 64
def changeBG(path):
"""Change background depending on bit size"""
if is_64bit_windows():
ctypes.windll.user32.SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, PATH, 3)
else:
ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, PATH, 3)
changeBG(PATH)
Update:
I've made an oversight with the above. As @Mark Tolonen demonstrated in the comments, it depends on ANSI and UNICODE path strings, not the OS type.
If you use the byte strings paths, such as b'C:\\Users\\Patrick\\Desktop\\0200200220.jpg'
, use:
ctypes.windll.user32.SystemParametersInfoA
Otherwise you can use this for normal unicode paths:
ctypes.windll.user32.SystemParametersInfoW
This is also highlighted better with argtypes in @Mark Tolonen's answer, and this other answer.
回答2:
SystemParametersInfoA
takes an ANSI string (bytes
type in Python 3).
SystemParametersInfoW
takes a Unicode string (str
type in Python 3).
So use:
path = b'C:\\Users\\Patrick\\Desktop\\0200200220.jpg'
ctypes.windll.user32.SystemParametersInfoA(20, 0, path, 3)
or:
path = 'C:\\Users\\Patrick\\Desktop\\0200200220.jpg'
ctypes.windll.user32.SystemParametersInfoW(20, 0, path, 3)
You can set the argtypes to do parameter checking. The 3rd parameter is documented as LPVOID
but you can be more specific for type checking:
from ctypes import *
windll.user32.SystemParametersInfoW.argtypes = c_uint,c_uint,c_wchar_p,c_uint
windll.user32.SystemParametersInfoA.argtypes = c_uint,c_uint,c_char_p,c_uint
来源:https://stackoverflow.com/questions/53878508/change-windows-10-background-in-python-3