Weather Forecast GUI V1 (Python)

I think I’ve started to get to grips with GUI windows in Python, so I’m now going to go back and rework my weather forecast so that it uses a GUI. My first attempt takes a longitude and latitude input from the user. Currently it outputs back to the Python shell, so I’ll need to sort that next 🙂

——

#!/bin/python3

#geektechstuff

#Weather Forecasting with a GUI

#libraries to import

import json, requests

from tkinter import *

#variables

LAT=”

LON=”

url=”

#create window

root = Tk()

#sets the windows title

root.title(“geektechstuff weather forecast”)

#sets windows width x height

root.geometry(“450×150”)

#frame to hold the labels / buttons

app = Frame(root)

app.grid()

#create label for the title

GTSWF_label = Label(app,text=”GeekTechStuff Weather Forecaster”)

GTSWF_label.grid(row=0, column=0)

#create label for the latitude and a text input box

Lat_label = Label(app,text=”Enter Latitude:”)

Lat_label.grid(row=1, column=0)

app.lat_ent=Entry(app)

app.lat_ent.grid(row=1,column=1)

#create label for the longitude and a text input box

Lon_label = Label(app,text=”Enter Latitude:”)

Lon_label.grid(row=2, column=0)

app.lon_ent=Entry(app)

app.lon_ent.grid(row=2,column=1)

#define actions for the buttons

#closes the window

def button_action():

    root.destroy()

#gets the weather forecast

def get_weather():

    LAT=app.lat_ent.get()

    LAT=str(LAT)

    LON=app.lon_ent.get()

    LON=str(LON)

    #calls on the API of openweathermap.org

    url=’http://api.openweathermap.org/data/2.5/forecast?lat=’+LAT+’&lon=’+LON+’&APPID=XXXXXXXXXXXXXXXX’

    url=str(url)

    response=requests.get(url)

    response.raise_for_status()

    #Loads the JSON

    weatherData=json.loads(response.text)

    w=weatherData[‘list’]

    print(w[0][‘dt_txt’])

    print(w[0][‘weather’][0][‘main’],’-‘,w[0][‘weather’][0][‘description’])

    #Converts Kevlin into Celsius, as I’m more of a celsius person

    temp_c=w[0][‘main’][‘temp’]

    temp_c=float(temp_c)

    temp_c=temp_c-273.15

    print(‘Average temp in celsius:’,temp_c)

    

#Add button

button_exit = Button(app,text=”Exit”, command=button_action)

button_exit.grid(row=4, column=0)

button_generate = Button(app,text=”Forecast”, command=get_weather)

button_generate.grid(row=4, column=1)

    

#start event loop – creates the window with the above labels and buttons

root.mainloop()

———