Simple Weather Forecast App
Abstract
Simple Weather Forecast App is a Python project that fetches and displays weather forecasts for a given city. It demonstrates API integration, data parsing, and GUI development. This project is ideal for learning about REST APIs, JSON handling, and interactive desktop apps.
Prerequisites
- Python 3.6 or above
- requests (
pip install requests
pip install requests
) - tkinter (usually pre-installed)
Before you Start
Install Python and requests. Obtain a free API key from a weather service (e.g., OpenWeatherMap).
Getting Started
- Create a folder named
weather-forecast-app
weather-forecast-app
. - Create a file named
simple_weather_forecast_app.py
simple_weather_forecast_app.py
. - Copy the code below into your file.
⚙️ Simple Weather Forecast App
Simple Weather Forecast App
"""
Simple Weather Forecast App
A Python application that fetches and displays weather forecast data. Features include:
- Fetching weather data from an API.
- Displaying the forecast in a user-friendly format.
"""
import requests
from tkinter import Tk, Label, Entry, Button, messagebox
API_KEY = "your_openweathermap_api_key"
BASE_URL = "http://api.openweathermap.org/data/2.5/weather"
class WeatherForecastApp:
def __init__(self, root):
self.root = root
self.root.title("Simple Weather Forecast App")
Label(root, text="Enter City Name:").grid(row=0, column=0, padx=10, pady=10)
self.city_entry = Entry(root, width=30)
self.city_entry.grid(row=0, column=1, padx=10, pady=10)
Button(root, text="Get Weather", command=self.get_weather).grid(row=1, column=0, columnspan=2, pady=10)
self.result_label = Label(root, text="", wraplength=400, justify="left")
self.result_label.grid(row=2, column=0, columnspan=2, padx=10, pady=10)
def get_weather(self):
"""Fetch weather data for the entered city."""
city = self.city_entry.get()
if not city:
messagebox.showerror("Error", "Please enter a city name.")
return
params = {"q": city, "appid": API_KEY, "units": "metric"}
try:
response = requests.get(BASE_URL, params=params)
data = response.json()
if response.status_code == 200:
weather = data["weather"][0]["description"].capitalize()
temp = data["main"]["temp"]
feels_like = data["main"]["feels_like"]
humidity = data["main"]["humidity"]
result = (
f"Weather in {city}:\n"
f"Condition: {weather}\n"
f"Temperature: {temp}°C\n"
f"Feels Like: {feels_like}°C\n"
f"Humidity: {humidity}%"
)
self.result_label.config(text=result)
else:
messagebox.showerror("Error", data.get("message", "Failed to fetch weather data."))
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {e}")
def main():
root = Tk()
app = WeatherForecastApp(root)
root.mainloop()
if __name__ == "__main__":
main()
Simple Weather Forecast App
"""
Simple Weather Forecast App
A Python application that fetches and displays weather forecast data. Features include:
- Fetching weather data from an API.
- Displaying the forecast in a user-friendly format.
"""
import requests
from tkinter import Tk, Label, Entry, Button, messagebox
API_KEY = "your_openweathermap_api_key"
BASE_URL = "http://api.openweathermap.org/data/2.5/weather"
class WeatherForecastApp:
def __init__(self, root):
self.root = root
self.root.title("Simple Weather Forecast App")
Label(root, text="Enter City Name:").grid(row=0, column=0, padx=10, pady=10)
self.city_entry = Entry(root, width=30)
self.city_entry.grid(row=0, column=1, padx=10, pady=10)
Button(root, text="Get Weather", command=self.get_weather).grid(row=1, column=0, columnspan=2, pady=10)
self.result_label = Label(root, text="", wraplength=400, justify="left")
self.result_label.grid(row=2, column=0, columnspan=2, padx=10, pady=10)
def get_weather(self):
"""Fetch weather data for the entered city."""
city = self.city_entry.get()
if not city:
messagebox.showerror("Error", "Please enter a city name.")
return
params = {"q": city, "appid": API_KEY, "units": "metric"}
try:
response = requests.get(BASE_URL, params=params)
data = response.json()
if response.status_code == 200:
weather = data["weather"][0]["description"].capitalize()
temp = data["main"]["temp"]
feels_like = data["main"]["feels_like"]
humidity = data["main"]["humidity"]
result = (
f"Weather in {city}:\n"
f"Condition: {weather}\n"
f"Temperature: {temp}°C\n"
f"Feels Like: {feels_like}°C\n"
f"Humidity: {humidity}%"
)
self.result_label.config(text=result)
else:
messagebox.showerror("Error", data.get("message", "Failed to fetch weather data."))
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {e}")
def main():
root = Tk()
app = WeatherForecastApp(root)
root.mainloop()
if __name__ == "__main__":
main()
- Run the script:
python simple_weather_forecast_app.py
python simple_weather_forecast_app.py
Explanation
Code Breakdown
- Import modules
import requests
import tkinter as tk
import requests
import tkinter as tk
- Fetch weather data
def get_forecast(city):
# Fetch weather data from API
pass
def get_forecast(city):
# Fetch weather data from API
pass
- GUI for forecast display
root = tk.Tk()
root.title('Weather Forecast App')
# ...setup widgets for city input and forecast display...
root.mainloop()
root = tk.Tk()
root.title('Weather Forecast App')
# ...setup widgets for city input and forecast display...
root.mainloop()
Features
- Fetches weather forecast from API
- GUI for display
- Easy to extend for more features
How It Works
- User enters city name
- App fetches and displays forecast
GUI Components
- Label: Shows forecast info
- Entry box: For city input
- Button: Fetches forecast
Use Cases
- Daily weather updates
- Learn API integration
- Build custom weather dashboards
Next Steps
You can enhance this project by:
- Adding more weather details
- Supporting multiple cities
- Improving GUI design
- Adding charts or graphs
Enhanced Version Ideas
def add_graphs():
# Display weather trends
pass
def support_multiple_cities():
# Show forecasts for several cities
pass
def add_graphs():
# Display weather trends
pass
def support_multiple_cities():
# Show forecasts for several cities
pass
Troubleshooting Tips
- API key errors: Check your key
- No forecast displayed: Check city name and internet connection
- GUI not showing: Ensure Tkinter is installed
Conclusion
This project teaches API usage, JSON parsing, and GUI basics. Extend it for more features and better user experience.
Was this page helpful?
Let us know how we did