PyWin32: How to Set the Desktop Background on Windows

Back in my system administrator days, we were thinking about setting the user’s Window desktop background to a specific image on login. Since I was in charge of the login scripts, which were written in Python, I decided to do some research to find out if there was a way to do it. We will look at two different approaches to this task in this article. The code in this article was tested using Python 2.7.8 and PyWin32 219 on Windows 7.

For the first approach, you will need to go download a copy of PyWin32 and install it. Now let’s look at the code:

# based on
import win32api, win32con, win32gui
def setWallpaper(path):
    key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER,"Control Panel\\Desktop",0,win32con.KEY_SET_VALUE)
    win32api.RegSetValueEx(key, "WallpaperStyle", 0, win32con.REG_SZ, "0")
    win32api.RegSetValueEx(key, "TileWallpaper", 0, win32con.REG_SZ, "0")
    win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, path, 1+2)
if __name__ == "__main__":
    path = r'C:\Users\Public\Pictures\Sample Pictures\Jellyfish.jpg'

In this example, we use a sample image that Microsoft provides with Windows. In the code above, we eidt a Windows Registry key. You could do the first 3 lines using Python’s own _winreg module if you wanted to. The last line tells Windows to set the desktop to the image we provided.

Now let’s look at another approach that utilizes the ctypes module and PyWin32.

import ctypes
import win32con
def setWallpaperWithCtypes(path):
    # This code is based on the following two links
    cs = ctypes.c_buffer(path)
    ok = ctypes.windll.user32.SystemParametersInfoA(win32con.SPI_SETDESKWALLPAPER, 0, cs, 0)
if __name__ == "__main__":
    path = r'C:\Users\Public\Pictures\Sample Pictures\Jellyfish.jpg'

In this piece of code, we create a buffer object that we then pass to basically the same command as we did in the previous example, namely SystemParametersInfoA. You will note that we don’t need to edit the registry in this latter case. If you check out the links listed in the sample code, you will note that some users found that Windows XP only allowed bitmaps to be set as the desktop background. I tested with a JPEG on Windows 7 and it worked fine for me.

Now you can create your own script that changes the desktop’s background at random intervals! Or maybe you’ll just use this knowledge in your own system administration duties. Have fun!

Print Friendly, PDF & Email
  • alfonce.

    How about using python 2.6?