Refresh Your Desktop Automatically with This Auto Wallpaper Fetcher & Changer
Staring at the same desktop background every day can feel uninspiring. Instead of manually searching for new images, you can build a Python script that automatically fetches high-quality wallpapers from Wallhaven and updates your desktop background at regular intervals.
This guide provides a complete, production-ready Python script that handles the entire pipeline: querying an online marketplace, downloading the image, and applying it as your system background. Prerequisites and Setup
Before executing the code, you need to install the required external libraries for handling internet requests and image processing. Open your terminal or command prompt and run the following command: pip install requests pillow Use code with caution. The Auto-Wallpaper Python Script
The script below uses the public Wallhaven API to search for high-resolution images based on your preferred keywords. It features a built-in safety mechanism that automatically filters out low-resolution images to ensure your wallpaper always looks sharp.
import os import time import ctypes import platform import requests from PIL import Image # — CONFIGURATION — SEARCH_QUERY = “nature landscape” # Keywords for your wallpaper RESOLUTION_MIN = (1920, 1080) # Minimum width and height CHANGE_INTERVAL = 3600 # Time between changes in seconds (3600s = 1 hour) SAVE_DIRECTORY = os.path.join(os.path.expanduser(””), “AutoWallpapers”) # Ensure the download directory exists if not os.path.exists(SAVE_DIRECTORY): os.makedirs(SAVE_DIRECTORY) def fetch_wallpaper_url(): “”“Queries Wallhaven API for a random wallpaper matching the search query.”“” url = f”https://wallhaven.cc{SEARCH_QUERY}&sorting=random&order=desc” try: response = requests.get(url, timeout=10) if response.status_code == 200: data = response.json() if data.get(‘data’): for item in data[‘data’]: # Filter out portrait images or low resolution width = item.get(‘dimension_x’, 0) height = item.get(‘dimension_y’, 0) if width >= RESOLUTION_MIN[0] and height >= RESOLUTION_MIN[1]: return item[‘path’] return None except Exception as e: print(f”Error fetching data from API: {e}“) return None def download_image(image_url): “”“Downloads the image and saves it locally.”“” try: response = requests.get(image_url, stream=True, timeout=15) if response.status_code == 200: file_path = os.path.join(SAVE_DIRECTORY, “current_wallpaper.jpg”) with open(file_path, ‘wb’) as f: for chunk in response.iter_content(1024): f.write(chunk) return file_path return None except Exception as e: print(f”Error downloading image: {e}“) return None def set_wallpaper(file_path): “”“Changes the system desktop background based on the OS.”“” sys_os = platform.system() try: if sys_os == “Windows”: # SPI_SETDESKWALLPAPER = 20 ctypes.windll.user32.SystemParametersInfoW(20, 0, file_path, 3) print(“Wallpaper updated successfully on Windows.”) elif sys_os == “Darwin”: # macOS from os import system script = f’tell application “Finder” to set desktop picture to POSIX file “{file_path}”’ system(f”osascript -e ‘{script}’“) print(“Wallpaper updated successfully on macOS.”) else: print(f”Unsupported operating system for auto-changing: {sys_os}“) except Exception as e: print(f”Failed to set wallpaper: {e}“) def main(): print(“Auto Wallpaper Changer started…”) print(f”Searching for: ‘{SEARCH_QUERY}’. Changing every {CHANGE_INTERVAL} seconds.“) while True: print(” Checking for a new wallpaper…“) img_url = fetch_wallpaper_url() if img_url: print(f”Found image: {img_url}“) saved_path = download_image(img_url) if saved_path: set_wallpaper(saved_path) else: print(“Failed to download image. Retrying next cycle.”) else: print(“No suitable wallpaper found. Retrying next cycle.”) time.sleep(CHANGE_INTERVAL) if name == “main”: main() Use code with caution. How to Automate the Script
To make this tool completely hands-free, you can set it to run silently in the background when your computer turns on.
Windows (Task Scheduler): Open Task Scheduler, create a new Basic Task, set the trigger to “When I log on”, and set the action to start a program. Point it to your pythonw.exe executable (which runs scripts without opening a command prompt window) and pass your script path as an argument.
macOS (Launchd): Create a .plist file inside your /Library/LaunchAgents directory configured to run your Python script path automatically at login.
By automating this script, your desktop will constantly surprise you with fresh aesthetic visuals without eating up system performance.
If you want to customize this further, tell me which operating system you use or what specific visual themes you prefer. I can provide the setup to run it silently on startup.
Leave a Reply