Weather Forecast Application in Python with Real-Time Updates
Building a weather forecast application is one of the most exciting projects for Python beginners. This project combines several important programming concepts including API integration, graphical user interface (GUI) development, and data handling. In this comprehensive guide, we’ll create a complete weather application that fetches real-time weather data and provides a user-friendly interface.
A Weather App using Python is a simple desktop application built with Tkinter that shows real-time weather updates for any city using the OpenWeatherMap API. It also lets you save the weather data to an Excel file for future reference. This project is great for students who want to learn about APIs, GUI development, and data logging in Python.
Project Overview
| Attribute | Details |
|---|---|
| Project Name | Weather Application |
| Language Used | Python |
What You’ll Learn
By completing this weather forecast project, you will gain hands-on experience with:
- Working with REST APIs and JSON data
- Creating desktop applications using Tkinter
- Handling user input and validation
- Working with Excel files using Python libraries
- Error handling and exception management
- Date and time manipulation
Required Libraries and Setup
Before starting the project, you need to install the following Python libraries:
pip install requests
pip install tkinter
pip install openpyxl
pip install pillow
You’ll also need to get a free API key from OpenWeatherMap. Visit their website, create an account, and obtain your API key.
Step-by-Step Implementation
Step 1: Import Required Libraries
First, let’s import all the necessary libraries for our weather application:
import tkinter as tk
from tkinter import messagebox, ttk
import requests
import json
from datetime import datetime
import openpyxl
from openpyxl import Workbook
import os
Step 2: Create the Main Application Class
We’ll create a class-based structure for our weather application:
class WeatherApp:
def __init__(self, root):
self.root = root
self.root.title("Weather Forecast Application")
self.root.geometry("600x500")
self.root.configure(bg="#87CEEB")
# Your OpenWeatherMap API key
self.api_key = "YOUR_API_KEY_HERE"
self.base_url = "http://api.openweathermap.org/data/2.5/weather"
# Create data folder if it doesn't exist
if not os.path.exists("data"):
os.makedirs("data")
self.setup_ui()
def setup_ui(self):
# Title Label
title_label = tk.Label(self.root, text="Weather Forecast App",
font=("Arial", 20, "bold"),
bg="#87CEEB", fg="white")
title_label.pack(pady=10)
# City input frame
input_frame = tk.Frame(self.root, bg="#87CEEB")
input_frame.pack(pady=20)
tk.Label(input_frame, text="Enter City Name:",
font=("Arial", 12), bg="#87CEEB").pack(side=tk.LEFT)
self.city_entry = tk.Entry(input_frame, font=("Arial", 12), width=20)
self.city_entry.pack(side=tk.LEFT, padx=10)
search_btn = tk.Button(input_frame, text="Get Weather",
command=self.get_weather,
font=("Arial", 10), bg="#4CAF50", fg="white")
search_btn.pack(side=tk.LEFT)
# Weather display frame
self.weather_frame = tk.Frame(self.root, bg="#87CEEB")
self.weather_frame.pack(pady=20, padx=20, fill=tk.BOTH, expand=True)
Step 3: Implement Weather Data Fetching
This function handles the API call to OpenWeatherMap and processes the response:
def get_weather(self):
city = self.city_entry.get().strip()
if not city:
messagebox.showerror("Error", "Please enter a city name!")
return
try:
# Construct API URL
url = f"{self.base_url}?q={city}&appid={self.api_key}&units=metric"
# Make API request
response = requests.get(url, timeout=10)
if response.status_code == 200:
weather_data = response.json()
self.display_weather(weather_data)
self.log_to_excel(weather_data)
elif response.status_code == 404:
messagebox.showerror("Error", "City not found!")
else:
messagebox.showerror("Error", "Failed to fetch weather data!")
except requests.exceptions.RequestException as e:
messagebox.showerror("Error", f"Network error: {str(e)}")
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {str(e)}")
Step 4: Display Weather Information
This function creates a user-friendly display of weather data:
def display_weather(self, data):
# Clear previous weather info
for widget in self.weather_frame.winfo_children():
widget.destroy()
# Extract weather information
city_name = data['name']
country = data['sys']['country']
temp = data['main']['temp']
feels_like = data['main']['feels_like']
humidity = data['main']['humidity']
pressure = data['main']['pressure']
wind_speed = data['wind']['speed']
description = data['weather'][0]['description']
# Create weather display
city_label = tk.Label(self.weather_frame,
text=f"{city_name}, {country}",
font=("Arial", 18, "bold"),
bg="#87CEEB")
city_label.pack(pady=5)
temp_label = tk.Label(self.weather_frame,
text=f"Temperature: {temp}°C",
font=("Arial", 14),
bg="#87CEEB")
temp_label.pack(pady=2)
feels_label = tk.Label(self.weather_frame,
text=f"Feels like: {feels_like}°C",
font=("Arial", 12),
bg="#87CEEB")
feels_label.pack(pady=2)
desc_label = tk.Label(self.weather_frame,
text=f"Description: {description.title()}",
font=("Arial", 12),
bg="#87CEEB")
desc_label.pack(pady=2)
humidity_label = tk.Label(self.weather_frame,
text=f"Humidity: {humidity}%",
font=("Arial", 12),
bg="#