In this tutorial, we will create a weather app using Python and PySimpleGUI. PySimpleGUI is a simple yet powerful package for building GUI applications in Python. We will be using the OpenWeatherMap API to fetch weather data for a specific location.
Step 1: Install PySimpleGUI and requests
First, install PySimpleGUI and requests using pip:
pip install PySimpleGUI
pip install requests
Step 2: Get an API key from OpenWeatherMap
In order to use the OpenWeatherMap API, you will need to sign up for an account and obtain an API key. You can sign up for free at https://home.openweathermap.org/users/sign_up.
Step 3: Create a new Python file
Create a new Python file and import the necessary modules:
import requests
import PySimpleGUI as sg
Step 4: Create a GUI layout
We will create a simple GUI layout with a text input for the location and a submit button to fetch the weather data. Add the following code to create the layout:
layout = [
[sg.Text('Enter city name or ZIP code:'), sg.InputText()],
[sg.Submit(), sg.Cancel()],
[sg.Text(size=(40, 10), key='-OUTPUT-')]
]
Step 5: Create a window
Create a window using the layout we defined and run the event loop:
window = sg.Window('Weather App', layout)
while True:
event, values = window.read()
if event in (None, 'Cancel'):
break
if event == 'Submit':
location = values[0]
# Add code to fetch weather data
Step 6: Fetch weather data
Now, we will use the OpenWeatherMap API to fetch weather data for the specified location. Add the following code inside the ‘Submit’ event handler:
url = f'http://api.openweathermap.org/data/2.5/weather?q={location}&appid=YOUR_API_KEY&units=metric'
response = requests.get(url)
data = response.json()
if response.status_code == 200:
weather_desc = data['weather'][0]['description']
temp = data['main']['temp']
humidity = data['main']['humidity']
output = f'Weather: {weather_desc}nTemperature: {temp}°CnHumidity: {humidity}%'
window['-OUTPUT-'].update(output)
else:
window['-OUTPUT-'].update('Error fetching weather data')
Make sure to replace ‘YOUR_API_KEY’ with the API key you obtained from OpenWeatherMap.
Step 7: Run the application
Finally, run the application by calling the window.close()
method outside the event loop:
window.close()
That’s it! You have successfully created a weather app using Python and PySimpleGUI. You can further customize the GUI layout and add more features to enhance the app. Experiment with different API endpoints and data to display additional weather information.
Is this app going to stop working after the free trial is over?
thanks it worked 🙂
Hi bro, How to do targeted Email Scraping through python?
Cool 👍
Excellent video my friend.
I am having an issue with my program.
The code breaks at:
city = res['location']['name']
KeyError: 'location'
Warnings =
library stubs not installed for 'requests' or incompatible with Python3.10
python3 -m pip install types-requests
mypy –install-types