In this article, we’ll explore a Python program that changes your Windows desktop wallpaper based on current weather conditions or lets you tests with specific weather categories. The program integrates folder management, downloading images, interacting with an API, and testing.
It’s not a fully-fledged application but it is a fantastic seed project for learning Python and understanding how to combine multiple functionalities into a cohesive application.

Folder Creation and Organization
The program starts by ensuring proper organization with a dedicated directory for wallpapers:
WALLPAPER_DIR = os.path.join(os.getcwd(), "wpapers")
This line creates a folder named wpapers
in the current working directory if it doesn’t already exist. Using os.makedirs()
with exist_ok=True
ensures that the folder setup is set whether it exists or not, the program continues without errors. By creating a central repository for images, the program avoids clutter and simplifies file management.
Downloading Wallpaper Images
The program includes a predefined mapping of weather categories (e.g., cold
, hot
, rainy
) to corresponding image URLs:
WALLPAPER_MAP = {
"cold": [
{"name": "cold1.jpg", "url": "https://drive.google.com/uc?id=1nPBSV-hyki8gMuXZq5PKyNKz-3VRA5GG"},
{"name": "cold2.jpg", "url": "https://drive.google.com/uc?id=1fOXxpn52DECjGLVA-X7kC8VnKQ5ylzJx"},
],
...
}
Each entry links a weather type to downloadable .jpg
files hosted online in the C. C. Python Programming google drive. The download_wallpapers
function iterates through these mappings and downloads any missing wallpapers to the wpapers
directory:
for category, wallpapers in WALLPAPER_MAP.items():
for wallpaper in wallpapers:
file_path = os.path.join(WALLPAPER_DIR, wallpaper["name"])
if not os.path.exists(file_path):
response = requests.get(wallpaper["url"], stream=True)
with open(file_path, "wb") as file:
for chunk in response.iter_content(1024):
file.write(chunk)
What you’ll see the first-time running python app.py:
Downloading cold1.jpg...
Downloaded cold1.jpg to C:\wpchanger\wpapers\cold1.jpg
Downloading cold2.jpg...
Downloaded cold2.jpg to C:\wpchanger\wpapers\cold2.jpg
Downloading hot1.jpg...
Downloaded hot1.jpg to C:\wpchanger\wpapers\hot1.jpg
Downloading hot2.jpg...
Downloaded hot2.jpg to C:\wpchanger\wpapers\hot2.jpg
Downloading perfect1.jpg...
Downloaded perfect1.jpg to C:\wpchanger\wpapers\perfect1.jpg
Downloading perfect2.jpg...
Downloaded perfect2.jpg to C:\wpchanger\wpapers\perfect2.jpg
Downloading rainy1.jpg...
Downloaded rainy1.jpg to C:\wpchanger\wpapers\rainy1.jpg
Downloading rainy2.jpg...
Downloaded rainy2.jpg to C:\wpchanger\wpapers\rainy2.jpg
Downloading snow1.jpg...
Downloaded snow1.jpg to C:\wpchanger\wpapers\snow1.jpg
Downloading snow2.jpg...
Downloaded snow2.jpg to C:\wpchanger\wpapers\snow2.jpg
Downloading sunny1.jpg...
Downloaded sunny1.jpg to C:\wpchanger\wpapers\sunny1.jpg
Downloading sunny2.jpg...
Downloaded sunny2.jpg to C:\wpchanger\wpapers\sunny2.jpg
1. Use actual weather
2. Test a category
Choose an option (1 or 2):
Fetching Weather Data (Optional)
To make weather-based decisions, the program queries the OpenWeatherMap API:
params = {
"q": city,
"appid": API_KEY,
"units": "metric"
}
response = requests.get(BASE_URL, params=params)
The fetch_weather
function retrieves live weather data for a user-specified city, including temperature and weather descriptions. Proper error handling ensures that issues like invalid API keys or nonexistent cities don’t crash the program.
Note: It’s not necessary to use the OpenWeatherMap API, as you can test the code using keywords.
Categorizing Weather
Once the weather data is fetched, the program uses the categorize_weather
function to assign conditions to one of six categories:
if "snow" in description:
return "snowy"
elif "rain" in description or "drizzle" in description:
return "rainy"
elif "clear" in description and temp > 25:
return "sunny"
This logic maps descriptive data (like “clear sky” or “light rain”) and temperature thresholds to practical wallpaper categories. It ensures wallpapers are visually appropriate for the user’s environment.
Changing the Wallpaper
The program changes the desktop wallpaper using the Windows API:
windll.user32.SystemParametersInfoW(20, 0, wallpaper_path, 3)
The change_wallpaper
function randomly selects an image from the appropriate category and applies it. The use of random.choice
adds variety, ensuring the same wallpaper isn’t repeated.
Testing Functionality
For developers or users who want to explore without waiting for live weather data, the program offers a manual testing option:
print("Available categories: cold, hot, perfect, rainy, snowy, sunny")
category = input("Enter a category: ").strip()
change_wallpaper(category)
This feature enables testing and debugging by allowing users to select any category directly.
A Seed Project for Coders
This program is a foundational example of integrating APIs, file handling, and user interactivity in Python. Here are some key takeaways and potential extensions:
Learning API Integration:
- The program demonstrates how to interact with external services like OpenWeatherMap. Understanding HTTP requests and JSON parsing is critical for modern software development.
File and Folder Management:
- Using
os
for directory handling and organizing resources into a structured format is a best practice for scalable applications.
Dynamic User Interaction:
- By allowing both automated and manual control, the program bridges utility and testing, showing how to cater to different use cases.
Opportunities for Expansion:
- Add features like a GUI for easier interaction.
- Enhance the categorization logic to include more granular weather conditions (e.g., thunderstorms).
- Integrate with other APIs for even richer customization options, like seasonal themes.
Full Code:
import os
import random
import requests
from ctypes import windll
# Map categories to wallpapers with download URLs
WALLPAPER_MAP = {
"cold": [
{"name": "cold1.jpg", "url": "https://drive.google.com/uc?id=1nPBSV-hyki8gMuXZq5PKyNKz-3VRA5GG"},
{"name": "cold2.jpg", "url": "https://drive.google.com/uc?id=1fOXxpn52DECjGLVA-X7kC8VnKQ5ylzJx"},
],
"hot": [
{"name": "hot1.jpg", "url": "https://drive.google.com/uc?id=1uq3s33bPZmHgDKpFrH-5Q5Sdku6Xs2j2"},
{"name": "hot2.jpg", "url": "https://drive.google.com/uc?id=19mcLX_AC6zHgc_f11Cl4q_1MzKXVv0Gy"},
],
"perfect": [
{"name": "perfect1.jpg", "url": "https://drive.google.com/uc?id=1VeZJdmmaRPMjPT3rN0oXqO9Oe3chcXf8"},
{"name": "perfect2.jpg", "url": "https://drive.google.com/uc?id=186JhA9I5oTHnjm7SKa_RJFcOzw8XzpdK"},
],
"rainy": [
{"name": "rainy1.jpg", "url": "https://drive.google.com/uc?id=1RCr_MlpeEFxNwO0RpNu44dXDtq5i-KCK"},
{"name": "rainy2.jpg", "url": "https://drive.google.com/uc?id=1s-Iqlgzxhc-egYvcOeTnkFv4cnyU5EEf"},
],
"snowy": [
{"name": "snow1.jpg", "url": "https://drive.google.com/uc?id=11TpDM--v3UPF7QaX6ydNoqSy_BIcJJ3A"},
{"name": "snow2.jpg", "url": "https://drive.google.com/uc?id=1zP4kk-8hIUlV1WgnOuukoFJik-x61deA"},
],
"sunny": [
{"name": "sunny1.jpg", "url": "https://drive.google.com/uc?id=1nDQkuaBor4SDJXWY82l8pygKlGVMxEz5"},
{"name": "sunny2.jpg", "url": "https://drive.google.com/uc?id=109mV9lKeuoNFU71adkn1QSqDiOb0dt7m"},
],
}
# Wallpaper directory
WALLPAPER_DIR = os.path.join(os.getcwd(), "wpapers")
# API Config
API_KEY = "Your API Key" # Replace with your API key
BASE_URL = "http://api.openweathermap.org/data/2.5/weather"
def fetch_weather(city: str):
"""Fetch weather data from OpenWeatherMap API."""
params = {
"q": city,
"appid": API_KEY,
"units": "metric"
}
response = requests.get(BASE_URL, params=params)
response.raise_for_status()
return response.json()
def categorize_weather(weather_data):
"""Categorize weather based on temperature and conditions."""
temp = weather_data["main"]["temp"]
description = weather_data["weather"][0]["description"].lower()
if "snow" in description:
return "snowy"
elif "rain" in description or "drizzle" in description:
return "rainy"
elif "clear" in description and temp > 25:
return "sunny"
elif temp < 5:
return "cold"
elif 18 <= temp <= 25:
return "perfect"
else:
return "hot"
def set_wallpaper(wallpaper_path):
"""Set the desktop wallpaper."""
windll.user32.SystemParametersInfoW(20, 0, wallpaper_path, 3)
def download_wallpapers():
"""Download all wallpapers if not already present."""
os.makedirs(WALLPAPER_DIR, exist_ok=True)
for category, wallpapers in WALLPAPER_MAP.items():
for wallpaper in wallpapers:
file_path = os.path.join(WALLPAPER_DIR, wallpaper["name"])
if not os.path.exists(file_path):
print(f"Downloading {wallpaper['name']}...")
response = requests.get(wallpaper["url"], stream=True)
response.raise_for_status()
with open(file_path, "wb") as file:
for chunk in response.iter_content(1024):
file.write(chunk)
print(f"Downloaded {wallpaper['name']} to {file_path}")
def change_wallpaper(category):
"""Change the wallpaper based on the given category."""
wallpapers = WALLPAPER_MAP.get(category, [])
if not wallpapers:
print(f"No wallpapers found for category: {category}")
return
wallpaper = random.choice(wallpapers)["name"]
wallpaper_path = os.path.join(WALLPAPER_DIR, wallpaper)
if os.path.exists(wallpaper_path):
set_wallpaper(wallpaper_path)
print(f"Wallpaper set to: {wallpaper}")
else:
print(f"Wallpaper not found: {wallpaper_path}")
def main():
download_wallpapers()
print("1. Use actual weather\n2. Test a category")
choice = input("Choose an option (1 or 2): ").strip()
if choice == "1":
city = input("Enter your city: ").strip()
weather_data = fetch_weather(city)
category = categorize_weather(weather_data)
print(f"Weather categorized as: {category}")
change_wallpaper(category)
elif choice == "2":
print("Available categories: cold, hot, perfect, rainy, snowy, sunny")
category = input("Enter a category: ").strip()
change_wallpaper(category)
else:
print("Invalid choice.")
if __name__ == "__main__":
main()
Thank you for reading this article. I hope you found it helpful and informative. If you have any questions, or if you would like to suggest new Python code examples or topics for future tutorials, please feel free to reach out. Your feedback and suggestions are always welcome!
Happy coding!
Py-Core Python Programming
You can also find this article at Medium.com