14 – Real-World Python Projects – Weather App

🎯 Project Objective

Build a Weather Application that fetches real-time weather data (temperature, humidity, conditions, etc.) for any city using a public weather API and displays it through a GUI interface.

Skills Demonstrated:

  • Consuming REST APIs using requests
  • Parsing JSON data
  • GUI development using Tkinter
  • Error handling and user input validation

🧠 Project Overview

The Weather App allows users to:

  • Enter a city name
  • Fetch live weather information
  • Display details such as temperature, humidity, wind speed, and weather description

Use Cases:

  • Travel and outdoor planning
  • Dashboard integration for smart homes
  • Mobile or web weather widgets

🧩 Example Code – Weather App (Tkinter + API)

Note: This code automatically installs missing modules like requests.

import os
import sys
import subprocess

# Auto-install missing modules
def install(package):
    try:
        __import__(package)
    except ImportError:
        subprocess.check_call([sys.executable, "-m", "pip", "install", package])

install("requests")
install("tkinter")

import requests
import tkinter as tk
from tkinter import messagebox

# Replace with your OpenWeatherMap API key
API_KEY = "your_api_key_here"  # Get one free from https://openweathermap.org/api

def get_weather():
    city = city_entry.get()
    if not city:
        messagebox.showwarning("Input Error", "Please enter a city name.")
        return

    url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={API_KEY}&units=metric"

    try:
        response = requests.get(url)
        data = response.json()

        if data["cod"] != 200:
            messagebox.showerror("Error", f"City not found: {city}")
            return

        weather = data["weather"][0]["description"].capitalize()
        temperature = data["main"]["temp"]
        humidity = data["main"]["humidity"]
        wind_speed = data["wind"]["speed"]

        result_label.config(text=f"🌀️ {weather}\n🌑️ Temperature: {temperature}Β°C\nπŸ’§ Humidity: {humidity}%\n🌬️ Wind Speed: {wind_speed} m/s")

    except Exception as e:
        messagebox.showerror("Error", f"Failed to retrieve weather: {e}")

# GUI Setup
root = tk.Tk()
root.title("Weather App")
root.geometry("400x300")
root.resizable(False, False)

tk.Label(root, text="Enter City Name:", font=("Arial", 12)).pack(pady=10)
city_entry = tk.Entry(root, width=30, font=("Arial", 12))
city_entry.pack()

tk.Button(root, text="Get Weather", command=get_weather, font=("Arial", 12), bg="#4CAF50", fg="white").pack(pady=10)

result_label = tk.Label(root, text="", font=("Arial", 12), justify="center")
result_label.pack(pady=20)

root.mainloop()

🧩 Sample Output

Input:

City: London

Output (GUI):

🌀️ Weather: Clear sky
🌑️ Temperature: 15°C
πŸ’§ Humidity: 65%
🌬️ Wind Speed: 3.5 m/s

βš™οΈ How It Works

  1. The app sends an API request to OpenWeatherMap.
  2. The server returns a JSON response with weather details.
  3. The app extracts relevant info and displays it neatly.

🌍 API Setup Instructions

  1. Visit https://openweathermap.org/api
  2. Sign up (free) and get your API Key
  3. Replace the placeholder in the code: API_KEY = "your_api_key_here"
  4. Run the script β€” you’re good to go! πŸš€

πŸ’‘ Advanced Features to Try

  • 🌈 Add weather icons (sun, cloud, rain, etc.)
  • πŸ•’ Display local time of the city
  • πŸ“… Show 7-day forecast
  • πŸ“ Use geolocation to auto-detect current city
  • πŸ’Ύ Save recent search history

βœ… Key Features

  • Real-time API data
  • Error handling for invalid city names
  • Clean and responsive GUI
  • Auto-module installation
  • Extensible for mobile/web platforms

πŸ“˜ Learning Outcomes

Handling dynamic data in GUI applications

API request and response handling

Parsing JSON with Python

Building user-friendly Tkinter interfaces


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *