Home > database >  Trying to create a simple interface that allows us to get the temperature of a city using python( T
Trying to create a simple interface that allows us to get the temperature of a city using python( T

Time:12-22

from tkinter import *
import requests

root=Tk() 

root.title("WEATHER API")
root.geometry("400x400")
city=StringVar()
def getweather():
      CITY=city.get()
      api_id="abb8cea2239face8fbb7401add34d73e"

      URL="https://api.openweathermap.org/data/2.5/weather?" CITY "appid=" api_id
      response=requests.get(URL)
      weatherinfo = response.json()
      if weatherinfo['cod']!='404':
         temp_kelvin=weatherinfo['main']['temp']
         temp_celsius=temp_kelvin-273
         temp_farhenheit=temp_celsius *(9/5)   32
         Labelc=Label(temp_celsius)

         Labelf=Label(temp_farhenheit)
         Labelc.pack()
         Labelf.pack()
      else:
         error=Label(text="ERROR")
         error.pack()

city=Entry(root)
city.pack()
Mybutton=Button(root,text="CHECK STATS",command=getweather).pack()

root.mainloop()

To be very precise this is what I am getting temp_kelvin=weatherinfo['main']['temp'] KeyError: 'main' Im a beginner in python, Isn't this related to dictionaries if yes then why is it wrong. The syntax seems fine.

CodePudding user response:

The URL is incorrect, it should be:

URL = "https://api.openweathermap.org/data/2.5/weather?q=" CITY "&appid=" api_id

It is better to use f-string:

URL = f"https://api.openweathermap.org/data/2.5/weather?q={CITY}&appid={api_id}"

Also the following lines are incorrect:

Labelc=Label(temp_celsius)
Labelf=Label(temp_farhenheit)

It should be:

Labelc = Label(root, text=temp_celsius)
Labelf = Label(root, text=temp_farhenheit)

And I would suggest to change this line:

if weatherinfo['cod'] != '404':

to:

if weatherinfo['cod'] == 200:

CodePudding user response:

I would like to add to acw1668's corrections.

It is preferable to import tkinter as tk instead of doing from tkinter import *. This is going to help prevent overwriting of defined objects down the road as your code grows.

Next I would change some of your case sensitivity. For example URL is all uppercase and in python like most languages this is to indicate a CONSTANT. Even though python does not have constants it is best practice to only use upper case like this if you intend for something to be treated like a constant in your code.

Next I would change all other labels to follow PEP8 standards. For example Labelc should look like label_c.

Next it appears that you first intended to use city = tk.StringVar() to hold your city value however you later define city = Entry(). It looks like you do not realize this is overwriting the first instance and the fact that city.get() is still working for you is due to the fact that both Entry() and StringVar() use get() to pull values form them so you may not have noticed this mistake. You can either use Entry() combined with get() or write it in a way that lets you use the string var in the entry field like this tk.Entry(root, textvariable=city).

One last thing. In this case it is probably best to use a try/except statement to handle errors since you have the potential for a few things to fail. This will allow your code to have an error and print to console without causing any unwanted behavior if the url request fails.

Here is a an example of my changes combined with acw1668's into a workable code.

import tkinter as tk
import requests


root = tk.Tk()
root.title('WEATHER API')
root.geometry('250x100')
city = tk.StringVar()
tk.Entry(root, textvariable=city).pack()


def get_weather():
    try:
        api_id = 'abb8cea2239face8fbb7401add34d73e'
        url = f'https://api.openweathermap.org/data/2.5/weather?q={city.get()}&appid={api_id}'
        response = requests.get(url)
        weather_info = response.json()

        if weather_info['cod'] == 200:
            temp_kelvin = weather_info['main']['temp']
            temp_celsius = temp_kelvin-273
            temp_fahrenheit = temp_celsius * (9/5)   32
            tk.Label(text=temp_celsius).pack()
            tk.Label(text=temp_fahrenheit).pack()
    except BaseException as e:
        tk.Label(text=f'ERROR: {e}').pack()


tk.Button(root, text='CHECK STATS', command=get_weather).pack()
root.mainloop()

Results:

enter image description here

One other note for those that need to use a proxy if your network has some restrictions on it.

For me to make this code work my URL had to grab from http instead of https and I had to use an internal proxy address that you can add into your request.get() like this:

url = f'http://api.openweathermap.org/data/2.5/weather?q={city.get()}&appid={api_id}'
response = requests.get(url, proxies={'http': 'http://proxy.your_proxy_url_here.com:80'})
  • Related