0% found this document useful (0 votes)
14 views14 pages

Kedar Py 123

The document outlines the development of a Python-based weather notification application using the tkinter GUI toolkit and the OpenWeatherMap API. It details prerequisites, project structure, implementation steps, and error handling for fetching and displaying real-time weather data based on user input. The application features a user-friendly interface that allows users to enter city names and receive immediate weather updates, including temperature, humidity, and pressure.

Uploaded by

swamikedar835
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views14 pages

Kedar Py 123

The document outlines the development of a Python-based weather notification application using the tkinter GUI toolkit and the OpenWeatherMap API. It details prerequisites, project structure, implementation steps, and error handling for fetching and displaying real-time weather data based on user input. The application features a user-friendly interface that allows users to enter city names and receive immediate weather updates, including temperature, humidity, and pressure.

Uploaded by

swamikedar835
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Python Live Weather Notification Project Details

Our project focuses on creating a user-friendly weather notification application using Python and
tkinter GUI toolkit. Leveraging the OpenWeatherMap API, the application fetches real-time
weather data based on user-provided city names. It features an intuitive interface with a text
entry for city names and a button to fetch weather information. Users receive immediate updates
on temperature, humidity, pressure, and weather descriptions, empowering them to make
informed decisions about their daily plans.
Prerequisites for Python Live Weather Notification
Project

 Basic understanding of Python programming language

 Familiarity with GUI development using the tkinter library

 Knowledge of making HTTP requests using Python


libraries like requests

 Access to an OpenWeatherMap API key for fetching


weather data

 Comfortable with handling exceptions and error messages


in Python


Python Project File Structure
1. Importing necessary libraries and modules

2. Defining the application logic:

 Creating the tkinter GUI: Implement the


WeatherNotificationApp class in gui.py to initialize and set
up the GUI components.

 Fetching weather data: Define functions in api.py to


interact with the OpenWeatherMap API (get_weather
function).

3. Running the application.


Step-by-Step Implementation of Python Live
Weather Notification Project

Importing necessary libraries and modules

import tkinter as tk
from tkinter import messagebox
import requests
import threading
import time

 tkinter (tk): Provides the GUI framework.

 messagebox: Part of tkinter for displaying pop-up


message boxes to show errors or notifications.

 requests: Used to make HTTP requests to fetch weather


data from the OpenWeatherMap API.

 threading: Enables running the weather fetching function


(show_weather) periodically in the background without
blocking the GUI.

 time: Used for time-related operations, such as


implementing a delay between periodic weather updates.
Defining functions for weather data and GUI interaction

def get_weather(city_name, api_key):


try:
base_url =
f"http://api.openweathermap.org/data/2.5/weather?q={city_name}&appid={
api_key}&units=metric"
response =
requests.get(base_url)
response.raise_for_status() # Raise an error for bad
responses
return response.json()
except requests.exceptions.RequestException as e:
messagebox.showerror("Error", f"Failed to fetch weather data:
{e}")
return None

 get_weather(city_name, api_key): Sends a request to


OpenWeatherMap

 API with city_name and api_key, retrieves weather data


in JSON format, and handles exceptions such as network
errors or invalid responses.
Function to show weather information

def show_weather():
city_name = city_entry.get()
api_key = "c319e74062fe9792cbe5db8ef2cce667" # Replace with your
OpenWeatherMap API key
if not city_name:
messagebox.showerror("Error", "Please enter a city name.")
return

weather_data = get_weather(city_name, api_key)


if weather_data and weather_data.get("cod") != "404":
main = weather_data["main"]
weather_desc = weather_data["weather"][0]["description"]
temp = main["temp"]
pressure = main["pressure"]
humidity = main["humidity"]

weather_info = f"City: {city_name}\nTemperature:


{temp}°C\nPressure: {pressure} hPa\nHumidity:
{humidity}%\nDescription: {weather_desc}"

# Display weather info in a message box


messagebox.showinfo("Weather Information", weather_info)
else:
messagebox.showerror("Error", "City Not Found")

 Purpose: Retrieves the city name from city_entry, fetches weather


data using get_weather, and displays temperature, pressure, humidity,
and weather description in a message box.

 Validation: Checks if a city name is entered (if not city_name) and


shows an error message if empty.

Error Handling: Handles cases where the city is not found


(“cod” != “404”) by displaying a relevant error message.
Creating the main application window and widgets

root = tk.Tk()
root.title("Live Weather Notifications")
root.geometry("400x200")

city_label = tk.Label(root, text="Enter City Name:")


city_label.pack(pady=5)

city_entry = tk.Entry(root, width=30)


city_entry.pack(pady=5)

notify_button = tk.Button(root, text="Get Weather",


command=show_weather)
notify_button.pack(pady=10)

 root = tk.Tk(): Creates the main application window.

 root.title(“Live Weather Notifications”): Sets the title of the

window.

 root.geometry(“400x200”): Defines the window's initial size.

 city_label, city_entry, notify_button: Widgets were added to the

root for user interaction (Label for text, entry for input, button for

triggering show_weather function).


import tkinter as tk
from tkinter import messagebox
import requests
import threading
import time

# Function to get weather data


def get_weather(city_name, api_key):
try:
base_url =
f"http://api.openweathermap.org/data/2.5/weather?q={city_name
}&appid={api_key}&units=metric"
response = requests.get(base_url)
response.raise_for_status() # Raise an error for bad
responses
return response.json()
except requests.exceptions.RequestException as e:
messagebox.showerror("Error", f"Failed to fetch
weather data: {e}")
return None

# Function to show weather notification


def show_weather():
city_name = city_entry.get()
api_key = "c319e74062fe9792cbe5db8ef2cce667" # Replace
with your OpenWeatherMap API key
if not city_name:
messagebox.showerror("Error", "Please enter a city
name.")
return

weather_data = get_weather(city_name, api_key)


if weather_data and weather_data.get("cod") != "404":
main = weather_data["main"]
weather_desc =
weather_data["weather"][0]["description"]
temp = main["temp"]
pressure = main["pressure"]
humidity = main["humidity"]
weather_info = f"City: {city_name}\nTemperature:
{temp}°C\nPressure: {pressure} hPa\nHumidity:
{humidity}%\nDescription: {weather_desc}"

# Display weather info in a message box


messagebox.showinfo("Weather Information",
weather_info)
else:
messagebox.showerror("Error", "City Not Found")

# Create the main window


root = tk.Tk()
root.title("Live Weather Notifications")
root.geometry("400x200")

# Add widgets to the window


city_label = tk.Label(root, text="Enter City Name:")
city_label.pack(pady=5)

city_entry = tk.Entry(root, width=30)


city_entry.pack(pady=5)

notify_button = tk.Button(root, text="Get Weather",


command=show_weather)
notify_button.pack(pady=10)

# Run the GUI event loop


root.mainloop()
Python Live Weather Notification Output
Conclusion

This code sets up a simple Tkinter-based GUI application for


fetching and displaying weather information using data from
the OpenWeatherMap API. It includes functions for making
API requests (get_weather) and showing weather data
(show_weather), and integrates them into a user-friendly
interface with labels, entry fields, and a button for user
interaction. The application’s main loop (root.mainloop())
ensures continuous responsiveness to user input and updates.
refrence
 openwhethermap api
 live whether

You might also like