icekiller8002 icekiller8002 - 24 days ago 12
Python Question

How do I set the desktop background in python? (windows)

This is what I'm trying:

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)


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

Answer

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))

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.

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.