首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python tkinter天气应用程序不显示天气

Python tkinter天气应用程序不显示天气
EN

Stack Overflow用户
提问于 2022-08-18 00:55:30
回答 1查看 53关注 0票数 0

在python中的这个天气应用程序中,我似乎可以使用tkinter窗口来工作。然而,当我键入一个城市,以获得通过我的api键的天气。我只得到了“天气___找不到”这句话。我试过了,只是在终端机上得到了响应,这似乎是可行的。我怎样才能让它工作,这样它就能让我在平纹橱窗里看到想要的城市的天气如何?

代码语言:javascript
复制
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()

我在“不活动”中提供的api密钥,但我使用的不是。

这是我为一个非平移天气程序使用的代码,这似乎是没有地质坐标的工作。

代码语言:javascript
复制
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.")
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-08-18 01:57:17

看起来您的API URL不正确。看看https://openweathermap.org/current的文档,上面写着:

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

lat, lon 地理坐标(纬度、经度)。如果您需要地理编码器自动转换城市名称和邮政编码到地理坐标和反过来,请使用我们的地理编码API。

基于此,您需要首先使用地理编码API将城市转换为纬度和经度坐标。在这里可以找到指向它的链接,https://openweathermap.org/api/geocoding-api

我认为您的代码应该做的是:

代码语言:javascript
复制
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

请注意地理编码API的URL字符串中的{STATE_CODE}和{COUNTRY_CODE}参数。这些都是可选的,可以删除。我会看医生的。如果您只输入城市名称,您可能会得到来自不同国家或州的多个城市。如果指定州代码或国家代码,这将有助于缩小搜索范围。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73396353

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档