8
votes

Does anyone know a way to change the Windows Desktop Wallpaper with python so that the change is permanent? I have found this code

import ctypes
SPI_SETDESKWALLPAPER = 20 
ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, "myimage.jpg" , 0)

This code works, but once you log off and log on again, the background is back to the original image. I would prefer a solution that does not require any registry edit, and I would like something that works with Windows XP and 7 if it is possible.

1
Could it be that the wallpaper setting is set to dynamic. Changes wallpapers after some time. - user568109
Hmmm. I ran the python script again, it changes the background image, but the image selected is still the old image... - Michael Bell
The last parameter, fWinIni, "specifies whether the user profile is to be updated". The flags are SPIF_UPDATEINIFILE == 1 and SPIF_SENDCHANGE == 2. The latter broadcasts a WM_SETTINGCHANGE message. Try using fWinIni == 3. - Eryk Sun
@eryksun changing it to 3 causes my background to become black on the next login. The Desktop background window shows that my background is now a file called myimage which is a black window. - Michael Bell
Are using an absolute path? "myimage.jpg" probably works at first because it's relative to the current working directory of your process. - Eryk Sun

1 Answers

3
votes

This solution combines several of the comments made, and works for me:

import ctypes
import os
drive = "C:\\"
folder = "images"
image = "test.jpg"
image_path = os.path.join(drive, folder, image)
SPI_SETDESKWALLPAPER = 20 
ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, image_path, 3)

(Note that you should determine the absolute path to your image, and change as needed. Also convert the image to BMP if you need to use it on XP. You can easily convert the image using Pillow)