Python wallpaper changer

With all those cool images I have sitting around on my computer it is often difficult to decide which to choose for my desktop. After a while I wondered if it would be possible to have Python select a random image from my wallpaper folder and set it as background. I digged around a bit and found a function SystemParametersInfo in user32.dll. After some hassles with the parameters I finally managed to create this piece of code to change wallpaper on the fly. Required modules are win32all and ctypes (for dll loading functions) as well as Python Imaging Library (to convert images to .BMP).

Code:


import Image
from win32con import SPI_SETDESKWALLPAPER, SPIF_SENDCHANGE, SPIF_UPDATEINIFILE
from ctypes import windll, WinError

def set_wallpaper(filename):

    try:
        # Convert image to .bmp
        img = Image.open(filename)
        destination = r'C:\Windows\Wallpaper.bmp'
        img.save(destination)

        # Update wallpaper with SystemParametersInfo
        SPIF_TELLALL = SPIF_SENDCHANGE | SPIF_UPDATEINIFILE
        if not windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0,
                                                   destination, SPIF_TELLALL):
            raise WinError(descr = 'Error while setting wallpaper %s' % filename)
   
     except IOError, ioe:
        # Intercept errors when image could not be converted to .bmp, e.g. when the file is truncated or corrupt
        pass

Leave a Reply