|

Automate Your Desktop: Create a Custom Wallpaper Changer with Python

3D isometric illustration of a robot changing a computer desktop wallpaper automatically based on a schedule.

Why manually change your wallpaper when Python can do it for you? In this project, we’ll write a script that picks a random image from a folder and sets it as your desktop background on Windows.

Note: This tutorial uses the ctypes library to talk to Windows directly. It currently only works on Windows.

Step 1: The Setup

We need os to find files, random to pick one, and ctypes to tell Windows to change the setting.

import ctypes
import os
import random

# Path to your folder of wallpapers (CHANGE THIS!)
WALLPAPER_FOLDER = r"C:\Users\YourName\Pictures\Wallpapers"

Step 2: Pick a Random Image

We need to get a list of all valid images in that folder.

def get_random_wallpaper(folder):
    # Get all files in the folder
    all_files = os.listdir(folder)
    
    # Filter for just images (jpg, png, bmp)
    images = [f for f in all_files if f.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp'))]
    
    if not images:
        print("No images found in that folder!")
        return None
        
    # Pick one at random
    random_image = random.choice(images)
    
    # Return the FULL path to the image
    return os.path.join(folder, random_image)

Step 3: The Magic Command (ctypes)

This is the obscure Windows command that does the actual work. Don’t worry if it looks weird; it’s just standard boilerplate for talking to the Windows API.

def set_wallpaper(image_path):
    # SPI_SETDESKWALLPAPER is the code Windows uses for this action
    SPI_SETDESKWALLPAPER = 20
    
    # Call the Windows system function
    # The '0' and '2' are standard flags for this specific call
    ctypes.windll.user32.SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, image_path, 2)
    print(f"Wallpaper changed to: {image_path}")

if __name__ == "__main__":
    new_wallpaper = get_random_wallpaper(WALLPAPER_FOLDER)
    if new_wallpaper:
        set_wallpaper(new_wallpaper)

Automation Tip

You can use Windows Task Scheduler to run this script automatically every morning at 9 AM!

Similar Posts

Leave a Reply