2 Sept 2023

How to Change Your Desktop Wallpaper in Windows 10 Using Python 🖼️

Do you ever get bored looking at your computer's same old wallpaper every day? 😕 Let's change it up and make your desktop exciting! 🖥️

We're going to show you how to make a magic wallpaper changer using Python! 🐍✨ It's easy-peasy, and even a 5-year-old can do it! 🧒🎉

Ready? Let's go on an adventure! 🚀🌟

Prerequisites

Before we get started, make sure you have the following prerequisites

  1. Basic knowledge of Python programming language.
  2. Python installed on your computer (https://www.python.org/downloads/)
  3. An internet connection to fetch new wallpapers.

Setting Up the Project

Let's begin by setting up the project structure. Open your favorite code editor and create a new folder for the project. Inside the folder, create the following files

  1. main.py : This will be our main Python script.
  2. config.py : Here, we'll store configurations for our wallpaper changer.
  3. wallpapers folder: This folder will hold the downloaded wallpapers.

Install Required Libraries

We'll need the requests library to fetch wallpapers from the internet. To install it, open your terminal or command prompt and run the following command

pip install requests

Import Necessary Modules

In the main.py file, import the required modules

import os
import random
import requests
from config import WALLPAPER_DIR, WALLPAPER_RESOLUTION, UNSPLASH_ACCESS_KEY

Fetching a New Wallpaper

For this project, we'll use Unsplash, a popular stock photo website, to fetch wallpapers. You'll need to create a free developer account on Unsplash to obtain an API access key. Once you have the access key, add it to the config.py  file

# config.py
WALLPAPER_DIR = "wallpapers"
WALLPAPER_RESOLUTION = "1920x1080"  # Change this to your screen resolution
UNSPLASH_ACCESS_KEY = "YOUR_UNSPLASH_ACCESS_KEY"

In the  main.py file, let's create a function to fetch a new wallpaper

def fetch_wallpaper():
    url = f"https://api.unsplash.com/photos/random?query=wallpaper&orientation=landscape&featured=true&resolution={WALLPAPER_RESOLUTION}"
    headers = {
        "Accept-Version": "v1",
        "Authorization": f"Client-ID {UNSPLASH_ACCESS_KEY}",
    }

    response = requests.get(url, headers=headers)
    if response.status_code == 200:
        return response.json()["urls"]["raw"]
    else:
        print("Failed to fetch wallpaper.")
      return None

Downloading the Wallpaper

Now that we have the URL of the new wallpaper, let's download it and save it in the  wallpapers folder 

def download_wallpaper(url, filename):
    response = requests.get(url)
    if response.status_code == 200:
        with open(filename, "wb") as f:
            f.write(response.content)
            print(f"Wallpaper downloaded: {filename}")
    else:
      print("Failed to download wallpaper.")

Changing the Wallpaper

We will use a Python library called  osascript to change the wallpaper on macOS. For Windows, we'll use the  ctypes library. Add the following functions to the main.py file 

def set_wallpaper_macos(file_path):
    os.system(f"osascript -e 'tell application \"Finder\" to set desktop picture to POSIX file \"{file_path}\"'")

def set_wallpaper_windows(file_path):
    import ctypes
  ctypes.windll.user32.SystemParametersInfoW(20, 0, file_path, 3)

Putting It All Together

Now, let's tie everything together in the main function

def main():
    # Ensure the wallpaper directory exists
    os.makedirs(WALLPAPER_DIR, exist_ok=True)

    # Fetch a new wallpaper
    wallpaper_url = fetch_wallpaper()

    if wallpaper_url:
        # Generate a random filename for the downloaded wallpaper
        file_name = f"{random.randint(1, 100000)}.jpg"
        file_path = os.path.join(WALLPAPER_DIR, file_name)

        # Download the wallpaper
        download_wallpaper(wallpaper_url, file_path)

        # Set the wallpaper based on the operating system
        if os.name == "posix":  # macOS
            set_wallpaper_macos(file_path)
        elif os.name == "nt":  # Windows
            set_wallpaper_windows(file_path)
        else:
            print("Unsupported operating system.")
          return

Automate the Process

To make sure your wallpaper changes daily, we'll use a scheduler to run our script automatically. One way to do this is by using the  schedule  library. Install it by running: pip install schedule

Now, let's modify the  main()  function to be called every day

import schedule
import time

def main():
    # ... (Previous code here) ...

# Schedule the main function to run every day at a specific time
schedule.every().day.at("08:00").do(main)

while True:
    schedule.run_pending()
  time.sleep(1)

With this modification, your wallpaper will be changed daily at 8:00 AM. Feel free to adjust the time as per your preference.

Running the Wallpaper Changer

To run the wallpaper changer, simply execute the  main.py file using Python: python main.py

The script will run in the background and change your desktop wallpaper daily according to the schedule you set.

Conclusion

Yay! 🎉 You did it! 🙌 You made a magic wallpaper changer with Python! 🪄 Now, your computer will surprise you with new, cool wallpapers every day, all by itself! 😃 No more clicking or searching for wallpapers! 🖥️

To make your wallpaper changer even cooler, you can:

  1. 💼 Add more systems: Make it work on different types of computers, not just one!
  2. 🌐 More wallpapers: Find even more places to get amazing wallpapers from! The more, the merrier! 🖼️
  3. ❤️ Personal touch: Let your computer know what kind of wallpapers you like, and it can pick them just for you! 🥰

Have lots of fun trying new things and keep coding! 🚀 Your computer is now your wallpaper artist! 🎨 Enjoy your ever-changing desktop world! 🌟