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
Right-click the upper-left corner of the Python console window and select Properties. In the dialog box that appears, pick the tab labeled Colors. On it you can set the screen background and text color. Save this answer.
The easiest way of running a python script to run in the background is to use cronjob feature (in macOS and Linux). In windows, we can use Windows Task Scheduler. You can then give the path of your python script file to run at a specific time by giving the time particulars.
import os pid = os. fork() if pid == 0: Continue to other code ... This will make the python process run in background. Save this answer.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With