問題描述
我一直在嘗試尋找通過 python 腳本更改 Windows 10 桌面壁紙的最佳方法.當我嘗試運行此腳本時,桌面背景變為純黑色.
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)
我能做些什么來解決這個問題?我正在使用python3
What can I do to fix this? I'm using python3
推薦答案
對于 64 位 windows,使用:
For 64 bit windows, use:
ctypes.windll.user32.SystemParametersInfoW
對于 32 位窗口,使用:
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)
更新:
我對上述內容進行了疏忽.正如評論中所展示的 @Mark Tolonen取決于 ANSI 和 UNICODE 路徑字符串,而不是操作系統類型.
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.
如果您使用字節字符串路徑,例如 b'C:\Users\Patrick\Desktop\0200200220.jpg'
,請使用:
If you use the byte strings paths, such as b'C:\Users\Patrick\Desktop\0200200220.jpg'
, use:
ctypes.windll.user32.SystemParametersInfoA
否則,您可以將其用于普通的 unicode 路徑:
Otherwise you can use this for normal unicode paths:
ctypes.windll.user32.SystemParametersInfoW
@Mark Tolonen 中的 argtypes 也可以更好地突出顯示這一點 答案,以及其他 answer.
這篇關于在 Python 3 中更改 Windows 10 背景的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!