How to Change My Desktop Background with Python

Change Windows 10 background in Python 3

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.

How to set the desktop background to a solid color programmatically

The correct way to do this is to call SystemParametersInfo SPI_SETDESKWALLPAPER with an empty string to remove the wallpaper and then call SetSysColors to change the desktop color. You probably need ctypes to do this in Python.

If you want to persist the change after log-off you also need to write the color to the registry.

Change Windows 10 Background Solid Color in Python

Instead of using IDesktopWallpaper, it is more simpler to use SetSysColors (from winuser.h header).

In Python, the code would look like this:

import ctypes
from ctypes.wintypes import RGB
from ctypes import byref, c_int

def changeSystemColor(color)
ctypes.windll.user32.SetSysColors(1, byref(c_int(1)), byref(c_int(color)))

if __name__ == '__main__':
color = RGB(255, 0, 0) # red
changeColor(color)

As stated in your post, you can do ctypes.windll.user32.SystemParametersInfoW(20, 0, "", 3) to remove the wallpaper image, exposing the solid background color that you can set with ctypes.windll.user32.SetSysColors.



Related Topics



Leave a reply



Submit