Home > Software design >  Python tkinter weather app not displaying weather
Python tkinter weather app not displaying weather

Time:08-19

In this weather app in python I seem to be able to have the tkinter window to work. However, when I type in a city to get the weather through my api key. All i get is the the else statement of "weather ___ not found." Ive tried it without tkinter, just getting the response in the terminal, and that seemed to work. How could I get get this to work so it shows me in the tkinter window what the weather is in the desired city?

import json
from tkinter.font import BOLD
import requests
from tkinter import *
from datetime import datetime
from PIL import ImageTk, Image

app = Tk()
app.title("Python Weather")
app.geometry("400x400")
app.resizable(0,0)
city_text = StringVar()
app.config(bg="#F7B511")

def time_format_for_location(utc_with_tz):
    local_time = datetime.utcfromtimestamp(utc_with_tz)
    return local_time.time()

city_value = StringVar()

def show_Weather():

    API_KEY = "a4c9d00da77f4bc855f0434165b0f63d"  
    city = city_text.get()
    URL = 'http://api.openweathermap.org/data/2.5/weather'   city 
      '&appid='  API_KEY
    response = requests.get(URL)
    tfield.delete("1.0", "end")
    weather_info = response.json()

    if weather_info['cod'] == 200:
        data = response.json()
        weather = data['weather'][0]['description']
        temperature = round(data['main']['temp']-273)
        temp_fahrenheit = temperature * 9 / 5   32
        print("Weather:", weather)
        print('temperature',temp_fahrenheit, "°f")
        weather = f"\nWeather of: {city}\nTemperature 
       (Fahrenheit): {temp_fahrenheit}°"
    else:
         weather = f"\n\tWeather for '{city}' not found."
     
         tfield.insert(INSERT, weather)

weather_displayed = Label(app, text =  "Enter Desired Location:", 
font = 'Georgia').pack(pady=10)

city_entry = Entry(app, textvariable=city_text, width = 24,
font='Georgia').pack()

Button(app,command=show_Weather, text="Search", font=('Times',20, 
'bold'), fg='black', 
activebackground="teal",padx=5, pady=5).pack(pady= 20)

tfield = Text(app, width=46, height=10)
tfield.pack()

app.mainloop()

The api key I provided in inactive but the one I use is not.

Here is the code I used for a non tkinter weather program, this seems to be working without geological coordinates.

import requests

API_KEY = 
"a4c9d00da77f4bc855f0434165b0f63d"
URL = 
"http://api.openweathermap.org 
/data/2.5/weather"

city = input("Enter a city name: ")
request_url = f"{URL}?appid={API_KEY}&q=. 
{city}"
response = requests.get(request_url)

if response.status_code == 200:
    data = response.json()
    weather = data['weather'][0]. 
    ['description']
    temperature = round(data['main']. 
    ['temp']-273)
    temp_fahrenheit = temperature * 9 / 5   
    32
    print("Weather:", weather)
    print('temperature',temp_fahrenheit, 
    "°f")
else:
    print("An error has occured.")

CodePudding user response:

It looks like your API URL is not correct. Looking at the docs at https://openweathermap.org/current, it says:

https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={API key}

[ lat, lon ] (required) Geographical coordinates (latitude, longitude). If you need the geocoder to automatic convert city names and zip-codes to geo coordinates and the other way around, please use our Geocoding API.

Based on this, it looks like you need to first convert the city to latitude and longitude coordinates using their geocoding API. The link to that can be found here, https://openweathermap.org/api/geocoding-api.

What I believe your code should do is the following:

def show_Weather():
    # first get the latitude and longitude coordinates of the city
    API_KEY = "a4c9d00da77f4bc855f0434165b0f63d"  
    city = city_text.get()
    URL = f'http://api.openweathermap.org/geo/1.0/direct?q={city},{STATE_CODE},
          {COUNTRY_CODE}&appid={API_KEY}'
    response = requests.get(URL)
    location_info = response.json()
    LAT = location_info[0]['lat']
    LON = location_info[0]['lon']

    # then get the weather from those coordinates
    URL = f'https://api.openweathermap.org/data/2.5/weather?lat={LAT}&lon= 
           {LON}&appid={API_KEY}'
    response = requests.get(URL)
    tfield.delete("1.0", "end")
    weather_info = response.json()

# rest of the code down here

Note the {STATE_CODE} and {COUNTRY_CODE} parameters in the URL string for the geocoding API. These are optional, and can be removed. I would read the docs. If you only put the city name in, you may get multiple cities from different countries or states. If you specify a state code or country code, this can help narrow down your search.

  • Related