{"id":27317,"date":"2022-01-31T15:17:55","date_gmt":"2022-01-31T15:17:55","guid":{"rendered":"https:\/\/www.askpython.com\/?p=27317"},"modified":"2023-02-16T19:56:44","modified_gmt":"2023-02-16T19:56:44","slug":"gui-weather-app-in-python","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python\/examples\/gui-weather-app-in-python","title":{"rendered":"Weather App in Python | Tkinter &#8211; GUI"},"content":{"rendered":"\n<p>In this tutorial, you will learn about how to create a GUI Weather App in Python. It uses Open Weather Map API to fetch the latest weather information of cities and places around the globe. Also, we will be implementing the weather app with GUI (Graphical User Interface) rather than the traditional boring ways, which are widely available, showing output in CLI(Command Line Interface).<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"code-for-weather-app-in-python-gui\">Code for Weather App in Python &#8211; GUI<\/h2>\n\n\n\n<p>Without further ado, let&#8217;s get right into the code setup for creating our GUI weather app in Python<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"1-install-and-import-tkinter\">1. Install and Import Tkinter <\/h3>\n\n\n\n<p>We begin with installing the required libraries using the <a href=\"https:\/\/www.askpython.com\/python-modules\/python-pip\" data-type=\"post\" data-id=\"3848\">pip package manager<\/a>. Enter the below commands in your command line or terminal to install the modules.<\/p>\n\n\n\n<p>We need to install:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/www.askpython.com\/python-modules\/requests-in-python\" data-type=\"post\" data-id=\"10001\">Request<\/a>: to fetch data from API<\/li><li><a href=\"https:\/\/www.askpython.com\/python-modules\/tkinter\/tkinter-font-class\" data-type=\"post\" data-id=\"22690\">Tkinter<\/a>: to make our Weather app GUI (Graphical User Interface) based.<\/li><li><a href=\"https:\/\/www.askpython.com\/python-modules\/python-datetime-module\" data-type=\"post\" data-id=\"6926\">DateTime<\/a>: to change the time from API to a different format<\/li><\/ul>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\npip install tkinter\npip install datetime\npip install requests\npip install json\n<\/pre><\/div>\n\n\n<p>After installing the required libraries from the terminal, we now move to our Python file to code. We start with importing the libraries as:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nfrom tkinter import *\nimport requests\nimport json\nfrom datetime import datetime\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\" id=\"2-initialize-the-tkinter-window\">2. Initialize the Tkinter Window<\/h3>\n\n\n\n<p>As a next step, we initialize our GUI window using the Tkinter module.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n#Initialize Window\n\nroot =Tk()\nroot.geometry(&quot;400x400&quot;) #size of the window by default\nroot.resizable(0,0) #to make the window size fixed\n#title of our window\nroot.title(&quot;Weather App - AskPython.com&quot;)\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\" id=\"3-openweathermap-api\">3. OpenWeatherMap API<\/h3>\n\n\n\n<p>In our code, we will be using Open Weather API (free tier) to get the current weather information which is accurate and latest.<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>To do so, go to <a href=\"https:\/\/openweathermap.org\/\" data-type=\"URL\" data-id=\"https:\/\/openweathermap.org\/\" target=\"_blank\" rel=\"noopener\">OpenWeatherMap<\/a> website and <strong>create <\/strong>an account.<\/li><li>After creating your account, go to profile and then &#8220;<strong>My API keys<\/strong>&#8220;.<\/li><li>This will open a webpage for your API <strong>Key<\/strong>, as shown below, copy it for later use in code in the next step.<\/li><\/ul>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"261\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2022\/01\/open-weather-api-1024x261.png\" alt=\"Open Weather Api\" class=\"wp-image-27378\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2022\/01\/open-weather-api-1024x261.png 1024w, https:\/\/www.askpython.com\/wp-content\/uploads\/2022\/01\/open-weather-api-300x77.png 300w, https:\/\/www.askpython.com\/wp-content\/uploads\/2022\/01\/open-weather-api-768x196.png 768w, https:\/\/www.askpython.com\/wp-content\/uploads\/2022\/01\/open-weather-api-1536x392.png 1536w, https:\/\/www.askpython.com\/wp-content\/uploads\/2022\/01\/open-weather-api.png 1806w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><figcaption>Open Weather Map API<\/figcaption><\/figure><\/div>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"4-weather-function\">4. Weather Function<\/h3>\n\n\n\n<p>Here, comes the part where we add functionality to our code. This part is the most crucial in getting correct weather information, as this involves fetching data from the API and displaying it in an accurate format.<\/p>\n\n\n\n<p>We code the most important function of this code, which is for displaying weather, we do so as in the code:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\ncity_value = StringVar()\n\ndef showWeather():\n\n#Enter you api key, copies from the OpenWeatherMap dashboard\n    api_key = &quot;eda2b2s6d#sd65f4de7c4b8&quot;  #sample API\n\n    # Get city name from user from the input field (later in the code)\n    city_name=city_value.get()\n\n    # API url\n    weather_url = &#039;http:\/\/api.openweathermap.org\/data\/2.5\/weather?q=&#039; + city_name + &#039;&amp;appid=&#039;+api_key\n\n    # Get the response from fetched url\n    response = requests.get(weather_url)\n\n    # changing response from json to python readable \n    weather_info = response.json()\n\n\n    tfield.delete(&quot;1.0&quot;, &quot;end&quot;)   #to clear the text field for every new output\n\n#as per API documentation, if the cod is 200, it means that weather data was successfully fetched\n\n\n    if weather_info&#x5B;&#039;cod&#039;] == 200:\n        kelvin = 273 # value of kelvin\n\n#-----------Storing the fetched values of weather of a city\n\n        temp = int(weather_info&#x5B;&#039;main&#039;]&#x5B;&#039;temp&#039;] - kelvin)                                     #converting default kelvin value to Celcius\n        feels_like_temp = int(weather_info&#x5B;&#039;main&#039;]&#x5B;&#039;feels_like&#039;] - kelvin)\n        pressure = weather_info&#x5B;&#039;main&#039;]&#x5B;&#039;pressure&#039;]\n        humidity = weather_info&#x5B;&#039;main&#039;]&#x5B;&#039;humidity&#039;]\n        wind_speed = weather_info&#x5B;&#039;wind&#039;]&#x5B;&#039;speed&#039;] * 3.6\n        sunrise = weather_info&#x5B;&#039;sys&#039;]&#x5B;&#039;sunrise&#039;]\n        sunset = weather_info&#x5B;&#039;sys&#039;]&#x5B;&#039;sunset&#039;]\n        timezone = weather_info&#x5B;&#039;timezone&#039;]\n        cloudy = weather_info&#x5B;&#039;clouds&#039;]&#x5B;&#039;all&#039;]\n        description = weather_info&#x5B;&#039;weather&#039;]&#x5B;0]&#x5B;&#039;description&#039;]\n\n        sunrise_time = time_format_for_location(sunrise + timezone)\n        sunset_time = time_format_for_location(sunset + timezone)\n\n#assigning Values to our weather varaible, to display as output\n        \n        weather = f&quot;\\nWeather of: {city_name}\\nTemperature (Celsius): {temp}\u00b0\\nFeels like in (Celsius): {feels_like_temp}\u00b0\\nPressure: {pressure} hPa\\nHumidity: {humidity}%\\nSunrise at {sunrise_time} and Sunset at {sunset_time}\\nCloud: {cloudy}%\\nInfo: {description}&quot;\n    else:\n        weather = f&quot;\\n\\tWeather for &#039;{city_name}&#039; not found!\\n\\tKindly Enter valid City Name !!&quot;\n\n\n\n    tfield.insert(INSERT, weather)   #to insert or send value in our Text Field to display output\n<\/pre><\/div>\n\n\n<p>As a final step to adding functionality, we add a function to change the time format, this function checks for the local time as compared to the UTC(<strong>Universal Time Coordinated<\/strong>) in which the API gives the output to the time format as per our location. Ex. UTC to IST.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\ndef time_format_for_location(utc_with_tz):\n    local_time = datetime.utcfromtimestamp(utc_with_tz)\n    return local_time.time()\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\" id=\"5-coding-the-gui-frontend-elements\">5. Coding the GUI (frontend elements)<\/h3>\n\n\n\n<p>We now start to code the elements as per the GUI, for heading, text, labels, buttons, etc.<\/p>\n\n\n\n<p>To start with, we code the <strong>text field<\/strong> for the <strong>City Name<\/strong> we want the weather for, along with the label to indicate so:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>We use the <strong><a href=\"https:\/\/www.askpython.com\/python-modules\/tkinter\/tkinter-frame-and-label\" data-type=\"post\" data-id=\"7522\">Label<\/a> <\/strong>method to generate a label of text to indicate the purpose of the input field for city name.<\/li><li><strong><a href=\"https:\/\/www.askpython.com\/python-modules\/tkinter\/tkinter-entry-widget\" data-type=\"post\" data-id=\"4911\">Entry<\/a> <\/strong>method is used to make an entry field for input of city name, to check its weather.<\/li><li>The textvaraible widget is used to store the inputted value, in the variable named: city_value<\/li><li>Other than these widgets we have also applied some styling to our code, by font size, color, etc.<\/li><\/ul>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\ncity_head= Label(root, text = &#039;Enter City Name&#039;, font = &#039;Arial 12 bold&#039;).pack(pady=10) #to generate label heading\n\ninp_city = Entry(root, textvariable = city_value,  width = 24, font=&#039;Arial 14 bold&#039;).pack() #entry field\n<\/pre><\/div>\n\n\n<p>We code a<strong> Check Weather Button<\/strong>, on which we click to check the weather of the user inputted city:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>We give our button some styling, along with the name \u2013 &#8216;Check Weather&#8217;. We use the &#8216;<strong>command<\/strong>&#8216; widget, which shows what function (here, <strong>showWeather <\/strong>function) would run on the click (key press) of the button, as coded in the previous step.<\/li><\/ul>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nButton(root, command = showWeather, text = &quot;Check Weather&quot;, font=&quot;Arial 10&quot;, bg=&#039;lightblue&#039;, fg=&#039;black&#039;, activebackground=&quot;teal&quot;, padx=5, pady=5 ).pack(pady= 20)\n<\/pre><\/div>\n\n\n<p>After adding this, we add the output elements in our code. The elements on which our Weather information would be displayed.<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Yet again, we add a label to title our result in the following text box<\/li><li>To display the output we use a <strong style=\"font-size: 1rem;background-color: var(--ast-global-color-5)\">text field<\/strong><span style=\"font-size: 1rem;background-color: var(--ast-global-color-5)\">, which gets its value, every time the &#8220;Check Weather&#8221; button is pressed. This envokes<\/span> the function to check weather info fetched from the API after processing, [output from the showWeather function]<\/li><\/ul>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nweather_now = Label(root, text = &quot;The Weather is: &quot;, font = &#039;arial 12 bold&#039;).pack(pady=10)\n\ntfield = Text(root, width=46, height=10)\ntfield.pack()\n<\/pre><\/div>\n\n\n<p>On execution of our code, the Tkinter displays this as output:<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full is-resized\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2022\/01\/Weather-app-frontend-in-python.png\" alt=\"Weather App Frontend In Python\" class=\"wp-image-27375\" width=\"364\" height=\"398\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2022\/01\/Weather-app-frontend-in-python.png 485w, https:\/\/www.askpython.com\/wp-content\/uploads\/2022\/01\/Weather-app-frontend-in-python-275x300.png 275w\" sizes=\"auto, (max-width: 364px) 100vw, 364px\" \/><figcaption>Weather App Frontend In Python<\/figcaption><\/figure><\/div>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"final-code-for-gui-weather-app-in-python\">Final Code for GUI Weather App in Python<\/h2>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nfrom tkinter import *\nimport requests\nimport json\nfrom datetime import datetime\n\n#Initialize Window\n\nroot =Tk()\nroot.geometry(&quot;400x400&quot;) #size of the window by default\nroot.resizable(0,0) #to make the window size fixed\n#title of our window\nroot.title(&quot;Weather App - AskPython.com&quot;)\n\n\n# ----------------------Functions to fetch and display weather info\ncity_value = StringVar()\n\n\ndef time_format_for_location(utc_with_tz):\n    local_time = datetime.utcfromtimestamp(utc_with_tz)\n    return local_time.time()\n\n\ncity_value = StringVar()\n\ndef showWeather():\n    #Enter you api key, copies from the OpenWeatherMap dashboard\n    api_key = &quot;eda2b2s6d#sd65f4de7c4b8&quot;  #sample API\n\n    # Get city name from user from the input field (later in the code)\n    city_name=city_value.get()\n\n    # API url\n    weather_url = &#039;http:\/\/api.openweathermap.org\/data\/2.5\/weather?q=&#039; + city_name + &#039;&amp;appid=&#039;+api_key\n\n    # Get the response from fetched url\n    response = requests.get(weather_url)\n\n    # changing response from json to python readable \n    weather_info = response.json()\n\n\n    tfield.delete(&quot;1.0&quot;, &quot;end&quot;)   #to clear the text field for every new output\n\n#as per API documentation, if the cod is 200, it means that weather data was successfully fetched\n\n\n    if weather_info&#x5B;&#039;cod&#039;] == 200:\n        kelvin = 273 # value of kelvin\n\n#-----------Storing the fetched values of weather of a city\n\n        temp = int(weather_info&#x5B;&#039;main&#039;]&#x5B;&#039;temp&#039;] - kelvin)                                     #converting default kelvin value to Celcius\n        feels_like_temp = int(weather_info&#x5B;&#039;main&#039;]&#x5B;&#039;feels_like&#039;] - kelvin)\n        pressure = weather_info&#x5B;&#039;main&#039;]&#x5B;&#039;pressure&#039;]\n        humidity = weather_info&#x5B;&#039;main&#039;]&#x5B;&#039;humidity&#039;]\n        wind_speed = weather_info&#x5B;&#039;wind&#039;]&#x5B;&#039;speed&#039;] * 3.6\n        sunrise = weather_info&#x5B;&#039;sys&#039;]&#x5B;&#039;sunrise&#039;]\n        sunset = weather_info&#x5B;&#039;sys&#039;]&#x5B;&#039;sunset&#039;]\n        timezone = weather_info&#x5B;&#039;timezone&#039;]\n        cloudy = weather_info&#x5B;&#039;clouds&#039;]&#x5B;&#039;all&#039;]\n        description = weather_info&#x5B;&#039;weather&#039;]&#x5B;0]&#x5B;&#039;description&#039;]\n\n        sunrise_time = time_format_for_location(sunrise + timezone)\n        sunset_time = time_format_for_location(sunset + timezone)\n\n#assigning Values to our weather varaible, to display as output\n        \n        weather = f&quot;\\nWeather of: {city_name}\\nTemperature (Celsius): {temp}\u00b0\\nFeels like in (Celsius): {feels_like_temp}\u00b0\\nPressure: {pressure} hPa\\nHumidity: {humidity}%\\nSunrise at {sunrise_time} and Sunset at {sunset_time}\\nCloud: {cloudy}%\\nInfo: {description}&quot;\n    else:\n        weather = f&quot;\\n\\tWeather for &#039;{city_name}&#039; not found!\\n\\tKindly Enter valid City Name !!&quot;\n\n\n\n    tfield.insert(INSERT, weather)   #to insert or send value in our Text Field to display output\n\n\n\n#------------------------------Frontend part of code - Interface\n\n\ncity_head= Label(root, text = &#039;Enter City Name&#039;, font = &#039;Arial 12 bold&#039;).pack(pady=10) #to generate label heading\n\ninp_city = Entry(root, textvariable = city_value,  width = 24, font=&#039;Arial 14 bold&#039;).pack()\n\n\nButton(root, command = showWeather, text = &quot;Check Weather&quot;, font=&quot;Arial 10&quot;, bg=&#039;lightblue&#039;, fg=&#039;black&#039;, activebackground=&quot;teal&quot;, padx=5, pady=5 ).pack(pady= 20)\n\n#to show output\n\nweather_now = Label(root, text = &quot;The Weather is:&quot;, font = &#039;arial 12 bold&#039;).pack(pady=10)\n\ntfield = Text(root, width=46, height=10)\ntfield.pack()\n\nroot.mainloop()\n<\/pre><\/div>\n\n\n<p>The Output of the GUI based Weather App is shown below:<\/p>\n\n\n\n<figure class=\"wp-block-video aligncenter\"><video controls muted src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2022\/01\/Output-for-Weather-app-in-Python.mp4\"><\/video><figcaption>Output for Weather App<\/figcaption><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"conclusion\">Conclusion<\/h2>\n\n\n\n<p>That&#8217;s it for the tutorial. Hope you have learned well how to make a Weather App in Python and that too with a level up by coding an Interface Based script along with API call (Open Weather Map) and Tkinter.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial, you will learn about how to create a GUI Weather App in Python. It uses Open Weather Map API to fetch the latest weather information of cities and places around the globe. Also, we will be implementing the weather app with GUI (Graphical User Interface) rather than the traditional boring ways, which [&hellip;]<\/p>\n","protected":false},"author":38,"featured_media":27394,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[9],"tags":[],"class_list":["post-27317","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-examples"],"blocksy_meta":[],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/27317","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/38"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=27317"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/27317\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media\/27394"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=27317"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=27317"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=27317"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}