Weather App in Python using Tkinter module

23 Jan, 2021
In this article, we are going to discuss how to create a weather app using tkinter. The GUI app will tell us the current weather of a particular city along with temperature details along with other details. 
Tkinter: It is a built-in python library for making GUI using tkinter toolkit.
Requests: It is a library which helps in fetching the data with the help of URL. It can be installed using the below command:
pip install requests
Firstly, we have to use a weather API for fetching the data from the Open Weather Map website by generating an API key, and then we need to create a configuration file to store the key. And finally using that configuration file in the python script.
Login in the Open Weather Map
Go to the API section. Then in the Current Weather Data section click on the Api doc.
Now in the API Call section, we have the link of api.openweathermap.org/data/2.5/weather?q={city name}&appid={API key}
Click on the API key on the link it will direct to the page from where you can get the key. The generated key looks like this:
Create a file named config.ini.
Write key name enclosed in closed brackets in it here [gfg].
Create a variable key(here key) and paste the key you copied as shown below:
Import modules.
Python3
# import required modulesfrom configparser import ConfigParserimport requestsfrom tkinter import *from tkinter import messagebox
We have to first make the body of the GUI with the help of tkinter.
Python3
# create objectapp = Tk()  # add titleapp.title("Weather App")  # adjust window sizeapp.geometry("300x300")  # add labels, buttons and textcity_text = StringVar()city_entry = Entry(app, textvariable=city_text)city_entry.pack()  Search_btn = Button(app, text="Search Weather",                    width=12, command=search)Search_btn.pack()  location_lbl = Label(app, text="Location",                      font={'bold', 20})location_lbl.pack()  temperature_label = Label(app, text="")temperature_label.pack()  weather_l = Label(app, text="")weather_l.pack()  app.mainloop()
Read the config.ini file and then load the key and URL in the program.
Python3
# extract key from the # configuration fileconfig_file = "config.ini"config = ConfigParser()config.read(config_file)api_key = config['gfg']['api']url = 'http://api.openweathermap.org/data/2.5/weather?q={}&appid={}'
Make a getweather() function to get the weather of a particular location.
Python3
# explicit function to get# weather detailsdef getweather(city):    result = requests.get(url.format(city, api_key))          if result:        json = result.json()        city = json['name']        country = json['sys']        temp_kelvin = json['main']['temp']        temp_celsius = temp_kelvin-273.15        weather1 = json['weather'][0]['main']        final = [city, country, temp_kelvin,                  temp_celsius, weather1]        return final    else:        print("NO Content Found")
Search function so that we can get the output weather details.
Python3
# explicit function to# search citydef search():    city = city_text.get()    weather = getweather(city)          if weather:        location_lbl['text'] = '{} ,{}'.format(weather[0], weather[1])        temperature_label['text'] = str(weather[3])+"   Degree Celsius"        weather_l['text'] = weather[4]              else:        messagebox.showerror('Error', "Cannot find {}".format(city))
Below is the complete program:
Python3
# import required modulesfrom configparser import ConfigParserimport requestsfrom tkinter import *from tkinter import messagebox  # extract key from the# configuration fileconfig_file = "config.ini"config = ConfigParser()config.read(config_file)api_key = config['gfg']['api']url = 'http://api.openweathermap.org/data/2.5/weather?q={}&appid={}'    # explicit function to get# weather detailsdef getweather(city):    result = requests.get(url.format(city, api_key))          if result:        json = result.json()        city = json['name']        country = json['sys']        temp_kelvin = json['main']['temp']        temp_celsius = temp_kelvin-273.15        weather1 = json['weather'][0]['main']        final = [city, country, temp_kelvin,                  temp_celsius, weather1]        return final    else:        print("NO Content Found")    # explicit function to# search citydef search():    city = city_text.get()    weather = getweather(city)    if weather:        location_lbl['text'] = '{} ,{}'.format(weather[0], weather[1])        temperature_label['text'] = str(weather[3])+"   Degree Celsius"        weather_l['text'] = weather[4]    else:        messagebox.showerror('Error', "Cannot find {}".format(city))    # Driver Code# create objectapp = Tk()# add titleapp.title("Weather App")# adjust window sizeapp.geometry("300x300")  # add labels, buttons and textcity_text = StringVar()city_entry = Entry(app, textvariable=city_text)city_entry.pack()Search_btn = Button(app, text="Search Weather",                     width=12, command=search)Search_btn.pack()location_lbl = Label(app, text="Location", font={'bold', 20})location_lbl.pack()temperature_label = Label(app, text="")temperature_label.pack()weather_l = Label(app, text="")weather_l.pack()app.mainloop()
Output:
Python Tkinter-exercises
Python Tkinter-projects
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python