0% found this document useful (0 votes)
53 views6 pages

Live Weather Desktop Notifications in Python

This document describes a Python project that uses APIs to get live weather data and send desktop notifications with weather details like temperature, humidity, and description for a given location. It discusses the modules used, project structure including setting up the GUI and button to get notifications, function to make API requests and extract weather values, and display them in a notification pop-up on the desktop.

Uploaded by

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

Live Weather Desktop Notifications in Python

This document describes a Python project that uses APIs to get live weather data and send desktop notifications with weather details like temperature, humidity, and description for a given location. It discusses the modules used, project structure including setting up the GUI and button to get notifications, function to make API requests and extract weather values, and display them in a notification pop-up on the desktop.

Uploaded by

Moses Adewara
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Live Weather Notifications using

Python
We all check for weather updates, especially when we want to go outside.
Wouldn’t it be more comfortable to get the notifications rather than checking
them ourselves? Yes! We will be building a Python project that sends live
weather reports as desktop notifications.

What is a Live Weather Desktop Notification


Project?
This weather desktop notification project sends the live weather report of the
location that you enter as a desktop notification. The information sent
includes temperature, pressure, humidity, and description if any.

Live Weather Desktop Notification Project using


Python
We will be building this project using the modules Tkinter, time, requests, and
plyer. We build the GUI to take the input of location using the Tkinter module.
Also, we use the requests module to extract the weather information from a
website. The time and plyer modules are used to send the notification and let
it pop up for a certain amount of time.

Prerequisites for Python Weather Alert Project


It is advised that the user has prior knowledge of python, Tkinter, and a
basic understanding of JSON format. The time module is a standard
python module. And the following commands can be used to download
the other modules.
pip install tkinter
pip install requests
pip install plyer

Project Structure
We will follow the below steps to build python weather alert project.
1. Importing modules
2. Creating a GUI and adding required components
3. Writing a function to get notification
Simple steps right? Now, let’s dive into the coding part.

1. Importing modules
#importing modules
import time
from tkinter import *
from tkinter import messagebox as mb
import requests
from plyer import notification
Code explanation:
a. In this step, we import the above discussed 4 modules
b. The message box helps in showing pop up message in case any error
occurred

2. Creating a GUI and adding required


components
Now, we create an empty window. Then we create the label, entry and
button for taking the input of the location and sending notification.
#creating the window
wn = Tk()
[Link]("PythonGeeks Weather Alert")
[Link]('700x200')
[Link](bg='azure')
# Heading label
Label(wn, text="PythonGeeks Weather Desktop Notifier", font=('Courier',
15), fg='grey19',bg='azure').place(x=100,y=15)
#Getting the city name
Label(wn, text='Enter the Location:', font=("Courier",
13),bg='azure').place(relx=0.05, rely=0.3)
place = StringVar(wn)
place_entry = Entry(wn, width=50, textvariable=place)
place_entry.place(relx=0.5, rely=0.3)
#Button to get notification
btn = Button(wn, text='Get Notification', font=7,
fg='grey19',command=getNotification).place(relx=0.4, rely=0.75)
#run the window till the closed by user
[Link]()
Code explanation:
a. title(): It displays the title on the top of the GUI.
b. config(): It sets the background color of the window
c. geometry(): It sets the length and width of the GUI.
d. Label(): This helps in showing text on the window
e. Entry(): This widget helps in taking input from the user
f. Button(): This creates a button with mentioned attributes and the
command parameter represents the function that executed on pressing
the button
g. mainloop(): This makes sure the screen runs till it is manually closed
3. Writing a function to get notification
Finally, we store the input of the place in a variable and generate a
corresponding link to get the information about weather conditions at
that location. Then, we get the json object and get the required details
like temperature, pressure, humidity, and description. At last, we show
this information in the form of a notification.
#Function to get notification of weather report
def getNotification():
cityName=[Link]() #getting input of name of the place from user
baseUrl = "[Link] #base url from
where we extract weather report
try:
# This is the complete url to get weather conditions of a city
url = baseUrl + "appid=" + 'd850f7f52bf19300a9eb4b0aa6b80f0d' + "&q=" +
cityName
response = [Link](complete_url) #requesting for the the content of the
url
x = [Link]() #converting it into json
y = x["main"] #getting the "main" key from the json object
# getting the "temp" key of y
temp = y["temp"]
temp-=273 #converting temperature from kelvin to celsius
# storing the value of the "pressure" key of y
pres = y["pressure"]
# getting the value of the "humidity" key of y
hum = y["humidity"]
# storing the value of "weather" key in variable z
z = x["weather"]
# getting the corresponding "description"
weather_desc = z[0]["description"]
# combining the above values as a string
info="Here is the eather description of "+ cityName+ ":"+" \nTemperature =
" +str(temp) +"°C"+"\n atmospheric pressure = " + str(pres) + "hPa"+"\n
humidity = " +str(hum) +"%"+"\n description of the weather= " +
str(weather_desc)
#showing the notification
[Link](
title = "YOUR WEATHER REPORT",
message=info ,
# displaying time
timeout=2)
# waiting time
[Link](7)
except Exception as e:
[Link]('Error',e)#show pop up message if any error occurred
Code explanation:
a. get(): It helps in getting the input given by the user in the Entry()
widget
b. [Link](): Getting the data from the url
c. .json(): converting data to .json format
d. [Link](): showing the notification on desktop
e. showerror(): Shows error pop up message on occurrence of exception

Output of Python Live Weather Desktop


Notification Project
Image of the desktop notification

Common questions

Powered by AI

Potential improvements include implementing location detection via IP to automatically fetch local weather data, integrating notifications with a voice assistant for accessibility, enabling more detailed weather information such as forecasts, and adding user settings for notification frequency and visible duration. Additionally, using internationalization for broader user accessibility and adapting the GUI for mobile platforms could significantly enhance the project's reach and functionality .

StringVar is significant in the GUI as it acts as a variable class in Tkinter to handle and manipulate strings, especially for input and output within the GUI. In the project, StringVar is used to store the user's input (city name), allowing dynamic updates and retrieval of the input value with get() method, which is essential for integrating real-time user data into the API call .

Setting up the GUI involves several steps: creating a window using Tk and setting its title, background color, and dimensions with title(), config(), and geometry() methods, respectively. A label is used to display the heading of the app, while another label and an Entry widget allow the user to enter the desired location. A button triggers the getNotification function. The mainloop() function keeps the window active until manually closed. These components together create an interactive and user-friendly interface for inputting data and receiving visual feedback .

The time module is used to introduce delays and set a timeout for the display of notifications. Specifically, notification.notify includes a 'timeout' parameter that determines how long the notification should be displayed on the screen. Additionally, time.sleep() is called to create pauses, ensuring the interface operates smoothly and users can read the notifications comfortably .

The getNotification function begins by retrieving the user's input for the city name using the Tkinter Entry widget. It constructs the API call URL by appending the user's inputted city name to the base URL of the weather API. Upon successfully making the request using the requests module, it processes the returned JSON data to extract weather information such as temperature, pressure, humidity, and description. This information is formatted into a string message. The function then uses plyer's notification.notify to display this information as a desktop notification for the user .

The Button widget in Tkinter is used to trigger the getNotification function. It enhances interactivity by allowing the user to initiate the weather data retrieval process with a simple click. The button is configured with a command parameter that binds it to the getNotification function, effectively linking the GUI action to backend processing. This interaction model is central to creating a responsive and user-oriented application .

Errors during the API request are handled using a try-except block. If an exception occurs, such as an unsuccessful API call or a network error, the showerror() function of tkinter's messagebox module is used to display a pop-up error message to the user. This provides instant visual feedback, alerting the user to any issues that need to be addressed for successful execution .

The primary modules used in the Python weather notification project are Tkinter, time, requests, and plyer. Tkinter is used to build the graphical user interface and to handle user input. The time module manages time-related tasks such as delays. The requests module is responsible for sending HTTP requests to fetch weather data from an API. Finally, the plyer module is used to create and display the desktop notifications .

From the API's JSON response, the data extracted includes 'temp' from the 'main' key, representing temperature, which is converted from Kelvin to Celsius by subtracting 273; 'pressure' key, indicating atmospheric pressure; 'humidity' key for humidity level; and the first element of the 'weather' key providing a description. These values are compiled into a formatted string using Python, which is then displayed as a desktop notification about the current weather conditions .

Prior knowledge of Python is necessary because the project involves scripting and understanding Python syntax and logic. Familiarity with Tkinter is advised as it handles GUI creation and user interaction in the project. Understanding the JSON format is crucial because weather data fetched from the API is in JSON, requiring manipulation and extraction of information to display the notification. Proficiency in these areas ensures efficient troubleshooting and successful project implementation .

You might also like