Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Create a GUI for weather forecast using weatherstack API in python
Weather forecasting is essential for daily planning and decision-making. The weatherstack API provides accurate weather data that can be integrated into Python applications. In this tutorial, we will create a graphical user interface (GUI) using tkinter to display real-time weather information.
Prerequisites
Before starting, ensure you have the following ?
Python 3.6 or higher installed
tkinter(usually comes with Python installation)requestslibrary:pip install requestsA free weatherstack API key from weatherstack.com
Setting Up the Weather GUI Application
Step 1: Import Required Libraries
import tkinter as tk from tkinter import messagebox import requests
We import tkinter for the GUI, messagebox for error handling, and requests for API calls.
Step 2: Configure API Settings
API_KEY = "your_weatherstack_api_key" API_URL = "http://api.weatherstack.com/current"
Replace your_weatherstack_api_key with your actual API key from weatherstack.
Step 3: Create the Main Window
root = tk.Tk()
root.title("Weather Forecast Application")
root.geometry("400x300")
root.configure(bg="#e6f3ff")
This creates the main window with a title, size, and background color.
Building the User Interface
Input Fields and Labels
# City input
city_label = tk.Label(root, text="City:", font=("Arial", 12), bg="#e6f3ff")
city_label.grid(row=0, column=0, padx=10, pady=10, sticky="w")
city_entry = tk.Entry(root, font=("Arial", 12), width=20)
city_entry.grid(row=0, column=1, padx=10, pady=10)
# Country input (optional)
country_label = tk.Label(root, text="Country (optional):", font=("Arial", 12), bg="#e6f3ff")
country_label.grid(row=1, column=0, padx=10, pady=10, sticky="w")
country_entry = tk.Entry(root, font=("Arial", 12), width=20)
country_entry.grid(row=1, column=1, padx=10, pady=10)
Weather Data Function
def get_weather():
city = city_entry.get().strip()
country = country_entry.get().strip()
if not city:
messagebox.showerror("Error", "Please enter a city name!")
return
# Build query string
query = f"{city},{country}" if country else city
url = f"{API_URL}?access_key={API_KEY}&query={query}"
try:
response = requests.get(url, timeout=10)
data = response.json()
if "error" in data:
messagebox.showerror("Error", f"API Error: {data['error']['info']}")
return
# Extract weather information
current = data["current"]
location = data["location"]
temperature = current["temperature"]
description = current["weather_descriptions"][0]
humidity = current["humidity"]
wind_speed = current["wind_speed"]
# Update display labels
location_info = f"{location['name']}, {location['country']}"
location_label.config(text=f"Location: {location_info}")
temperature_label.config(text=f"Temperature: {temperature}°C")
description_label.config(text=f"Description: {description}")
humidity_label.config(text=f"Humidity: {humidity}%")
wind_label.config(text=f"Wind Speed: {wind_speed} km/h")
except requests.RequestException:
messagebox.showerror("Error", "Network error! Check your internet connection.")
except KeyError:
messagebox.showerror("Error", "Invalid response from weather service.")
Button and Display Labels
# Get Weather button
get_weather_button = tk.Button(root, text="Get Weather", command=get_weather,
font=("Arial", 12), bg="#4CAF50", fg="white",
padx=20, pady=5)
get_weather_button.grid(row=2, column=0, columnspan=2, pady=20)
# Weather display labels
location_label = tk.Label(root, text="", font=("Arial", 11, "bold"), bg="#e6f3ff")
location_label.grid(row=3, column=0, columnspan=2, pady=5)
temperature_label = tk.Label(root, text="", font=("Arial", 14), bg="#e6f3ff", fg="#d32f2f")
temperature_label.grid(row=4, column=0, columnspan=2, pady=5)
description_label = tk.Label(root, text="", font=("Arial", 11), bg="#e6f3ff")
description_label.grid(row=5, column=0, columnspan=2, pady=5)
humidity_label = tk.Label(root, text="", font=("Arial", 10), bg="#e6f3ff")
humidity_label.grid(row=6, column=0, columnspan=2, pady=2)
wind_label = tk.Label(root, text="", font=("Arial", 10), bg="#e6f3ff")
wind_label.grid(row=7, column=0, columnspan=2, pady=2)
Complete Weather Application
import tkinter as tk
from tkinter import messagebox
import requests
# API Configuration
API_KEY = "your_weatherstack_api_key"
API_URL = "http://api.weatherstack.com/current"
# Create main window
root = tk.Tk()
root.title("Weather Forecast Application")
root.geometry("400x300")
root.configure(bg="#e6f3ff")
# Input fields
city_label = tk.Label(root, text="City:", font=("Arial", 12), bg="#e6f3ff")
city_label.grid(row=0, column=0, padx=10, pady=10, sticky="w")
city_entry = tk.Entry(root, font=("Arial", 12), width=20)
city_entry.grid(row=0, column=1, padx=10, pady=10)
country_label = tk.Label(root, text="Country (optional):", font=("Arial", 12), bg="#e6f3ff")
country_label.grid(row=1, column=0, padx=10, pady=10, sticky="w")
country_entry = tk.Entry(root, font=("Arial", 12), width=20)
country_entry.grid(row=1, column=1, padx=10, pady=10)
def get_weather():
city = city_entry.get().strip()
country = country_entry.get().strip()
if not city:
messagebox.showerror("Error", "Please enter a city name!")
return
query = f"{city},{country}" if country else city
url = f"{API_URL}?access_key={API_KEY}&query={query}"
try:
response = requests.get(url, timeout=10)
data = response.json()
if "error" in data:
messagebox.showerror("Error", f"API Error: {data['error']['info']}")
return
current = data["current"]
location = data["location"]
temperature = current["temperature"]
description = current["weather_descriptions"][0]
humidity = current["humidity"]
wind_speed = current["wind_speed"]
location_info = f"{location['name']}, {location['country']}"
location_label.config(text=f"Location: {location_info}")
temperature_label.config(text=f"Temperature: {temperature}°C")
description_label.config(text=f"Description: {description}")
humidity_label.config(text=f"Humidity: {humidity}%")
wind_label.config(text=f"Wind Speed: {wind_speed} km/h")
except requests.RequestException:
messagebox.showerror("Error", "Network error! Check your internet connection.")
except KeyError:
messagebox.showerror("Error", "Invalid response from weather service.")
# Button and display labels
get_weather_button = tk.Button(root, text="Get Weather", command=get_weather,
font=("Arial", 12), bg="#4CAF50", fg="white",
padx=20, pady=5)
get_weather_button.grid(row=2, column=0, columnspan=2, pady=20)
location_label = tk.Label(root, text="", font=("Arial", 11, "bold"), bg="#e6f3ff")
location_label.grid(row=3, column=0, columnspan=2, pady=5)
temperature_label = tk.Label(root, text="", font=("Arial", 14), bg="#e6f3ff", fg="#d32f2f")
temperature_label.grid(row=4, column=0, columnspan=2, pady=5)
description_label = tk.Label(root, text="", font=("Arial", 11), bg="#e6f3ff")
description_label.grid(row=5, column=0, columnspan=2, pady=5)
humidity_label = tk.Label(root, text="", font=("Arial", 10), bg="#e6f3ff")
humidity_label.grid(row=6, column=0, columnspan=2, pady=2)
wind_label = tk.Label(root, text="", font=("Arial", 10), bg="#e6f3ff")
wind_label.grid(row=7, column=0, columnspan=2, pady=2)
# Start the application
root.mainloop()
Key Features
Error handling Validates user input and handles API errors
Enhanced UI Improved styling with colors and fonts
Comprehensive data Shows temperature, humidity, wind speed, and description
Network timeout Prevents application freezing on slow connections
Conclusion
This weather application demonstrates how to integrate external APIs with Python GUI applications. The enhanced version includes proper error handling, improved styling, and additional weather data for a better user experience.
