In this project, we’ll create a Weather Forecasting Application using Python. The app will allow users to input a city name and get real-time weather data such as temperature, weather condition, humidity, wind speed, and more. We’ll use the Tkinter library for the GUI and the OpenWeatherMap API to fetch weather data.
1. Project Setup
Modules Required:
- tkinter: For the graphical user interface.
- requests: For making HTTP requests to the weather API.
Install the necessary modules:
pip install tkinter
pip install requests
Sign Up for OpenWeatherMap API:
- Go to the OpenWeatherMap website and sign up to get an API Key.
- This key will be used to authenticate and access weather data.
2. Project Features
- Get Real-time Weather Data: Users can enter a city name and get real-time weather information such as:
- Temperature (Celsius/Fahrenheit)
- Weather condition (e.g., Clear, Rain, Cloudy)
- Humidity
- Wind Speed
- Description (e.g., Light rain, scattered clouds)
- Graphical User Interface: Simple, intuitive GUI using Tkinter for user interaction.
- Error Handling: If the city is not found or API call fails, the app shows a meaningful error message.
3. Code Structure
We’ll divide the project into three main parts:
- Fetching Weather Data from the OpenWeatherMap API.
- Creating a GUI to input the city and display the weather information.
- Error Handling to ensure smooth operation.
4. Fetching Weather Data from OpenWeatherMap API
First, let’s write a function to fetch weather data for a given city using the API.
import requests
# Function to get weather data
def get_weather(city_name, api_key):
base_url = f"http://api.openweathermap.org/data/2.5/weather?q={city_name}&appid={api_key}&units=metric"
response = requests.get(base_url)
if response.status_code == 200:
data = response.json()
main = data['main']
weather = data['weather'][0]
wind = data['wind']
weather_data = {
"city": data['name'],
"temperature": main['temp'],
"humidity": main['humidity'],
"wind_speed": wind['speed'],
"weather_description": weather['description'],
"weather_main": weather['main']
}
return weather_data
else:
return None
5. Building the GUI using Tkinter
We’ll use Tkinter to create a simple interface for entering the city name and displaying the weather information.
A. Main Window
from tkinter import *
from tkinter import messagebox
import requests
# Function to get weather details and display it on the UI
def display_weather():
city = entry_city.get()
if city:
api_key = "your_openweathermap_api_key_here" # Replace with your API Key
weather = get_weather(city, api_key)
if weather:
label_city.config(text=f"City: {weather['city']}")
label_temperature.config(text=f"Temperature: {weather['temperature']}°C")
label_weather_main.config(text=f"Weather: {weather['weather_main']}")
label_description.config(text=f"Description: {weather['weather_description']}")
label_humidity.config(text=f"Humidity: {weather['humidity']}%")
label_wind_speed.config(text=f"Wind Speed: {weather['wind_speed']} m/s")
else:
messagebox.showerror("Error", "City not found or API error!")
else:
messagebox.showwarning("Input Error", "Please enter a city name.")
# Creating the main window
root = Tk()
root.title("Weather Forecasting App")
root.geometry("400x400")
# City input
Label(root, text="Enter City Name:", font=("Helvetica", 12)).pack(pady=10)
entry_city = Entry(root, width=25)
entry_city.pack(pady=5)
# Fetch Weather button
Button(root, text="Get Weather", command=display_weather).pack(pady=20)
# Labels for displaying weather info
label_city = Label(root, text="", font=("Helvetica", 14))
label_city.pack(pady=5)
label_temperature = Label(root, text="", font=("Helvetica", 12))
label_temperature.pack(pady=5)
label_weather_main = Label(root, text="", font=("Helvetica", 12))
label_weather_main.pack(pady=5)
label_description = Label(root, text="", font=("Helvetica", 12))
label_description.pack(pady=5)
label_humidity = Label(root, text="", font=("Helvetica", 12))
label_humidity.pack(pady=5)
label_wind_speed = Label(root, text="", font=("Helvetica", 12))
label_wind_speed.pack(pady=5)
root.mainloop()
6. Explanation of Code
A. Weather Data Fetching
The get_weather
function:
- Sends a request to the OpenWeatherMap API with the city name and API key.
- Extracts important weather information such as temperature, weather condition, humidity, wind speed, etc.
- Returns a dictionary containing this data if the city is found, otherwise returns
None
.
B. Graphical Interface (GUI)
- Tkinter is used to create the main application window.
- The user enters the city name in a text box.
- The weather data is fetched and displayed using labels in the window.
C. Handling Errors
- If the API cannot find the city or there is a network error, a messagebox is used to display an error message.
- If the input field is left blank, the app prompts the user to enter a city name.
7. Enhancements and Additional Features
You can extend this weather forecasting application with more features:
- Display Forecast for Multiple Days: Use OpenWeatherMap’s 5-day forecast API to show a forecast for the next several days.
- Toggle between Celsius and Fahrenheit: Allow users to choose between temperature units.
- Search History: Save previous searches and allow users to view the weather data for cities they’ve searched before.
- Weather Icons: Display weather icons (sunny, rainy, cloudy) based on the weather conditions using the icons provided by OpenWeatherMap.
- Styling the App: Enhance the design using custom colors, fonts, and frames to make the UI more appealing.
- Responsive Design: Adapt the layout to different screen sizes and make the interface responsive.
8. Conclusion
This is a basic Weather Forecasting App built with Python and Tkinter, leveraging the OpenWeatherMap API to fetch real-time weather data. The app allows users to get weather information by simply entering a city name. It can be extended with more advanced features, making it a useful tool for daily weather updates.
Would you like to see any specific enhancements or functionality added to this project?