我有我制作的天气应用程序。 我有两个问题。 Fist是让我像这样尝试我的代码,它工作得很好,第一部分。但问题是当他们有更多同名城市时。我看不到另一个,因为有了这行代码,我只能找到第一个字典
'''
from tkinter import *
import requests
import json
root = Tk()
root.title("Weather app")
root.geometry("550x400")
root.configure(background="green")
var = IntVar()
def citylookup():
try:
api_request = requests.get(
"http://dataservice.accuweather.com/locations/v1/cities/autocomplete?apikey="
"xxxxxxxxxxxyyyyyyyyyyxxxxxxxxxxx" + city_search.get() + "&language=fr-FR")
api = json.loads(api_request.content)
localisation = api[0]["LocalizedName"]
region_adm = api[0]["AdministrativeArea"]["ID"]
id_key = api[0]["Key"]
# citylabel = Label(root, text=localisation + ", " + region_adm)
# citylabel.grid(row=1, column=0, columnspan=2)
button = Button(root, text=localisation + ", " + region_adm, command=forecast)
button.grid(row=1, column=0)
except Exception as e:
api = "Error..."
def forecast():
try:
api_request2 = requests.get("http://dataservice.accuweather.com/forecasts/v1/daily/1day/"
+ id_key.get() + "?apikey=xxxxxxxxxxxyyyyyyyyyyxxxxxxxxxxxg&language="
"fr-FR&details=true&metric=true")
api2 = json.loads(api_request2.content)
temperature = api2[0]["Temperature"]["Metric"]["Value"]
humidite = api2[0]["RelativeHumidity"]
uvindex = api2[0]["UVIndex"]
precipitation = api2[0]["PrecipitationSummary"]["Precipitation"]["Metric"]["Value"]
mylabel = Label(root,text="Aujourd'hui il fait \n" + temperature + text + "\nL'humidité relative est de " + humidite + "%\n" + "L'index UV est de " + uvindex + "\nPrécipitation prévue " + precipitation)
mylabel.grid(row=3, column=0, columnspan=2)
except Exception as e:
api = "Error..."
city_search = Entry(root)
city_search.grid(row=0, column=0, stick=W+E+N+S)
city_button = Button(root, text="Ville rechercher", command=citylookup)
city_button.grid(row=0, column=1, stick=W+E+N+S)
root.mainloop()
'''
所以我在json文件中尝试了一个for循环。检索字典中的所有城市名称。(有些城市的名字有一个、其他3个、一些5个或更多。)
对于列表中的i(范围(0,10)): 本地化=api[i][«本地化名称»] 等等
但我只收到一个名字,是字典里的第二个名字。 我不知道这是我的错… 因此,对于第一个问题,我尝试,我要点击按钮“citylookup”,查看字典中所有可用的城市
我遇到的第二个问题是命令=forecast。 如果我让我的代码像这样运行,我会收到一条消息错误(未解析的引用“forecast”)
位如果我将我的函数“def forecast():”放置在没有缩进的位置就可以了预测没有错误,但是我收到了相同的消息error,带有id\u key.get()
如果我把我的函数放在函数citylookup()上:我在citylookup中收到一个(不使用id\u键),在函数“forecast”中收到一个(未解析的引用“id\u键”)
我想做的是点击一个城市,他们给我看天气预报
我不确定问题中代码的缩进是否与您的代码相同,但我会假设它是相同的
我不明白为什么要在
except
的范围内定义forecast()
函数。我建议首先把这个函数去掉例如:
这样,这两个函数都可用于整个文件,而不仅仅是单个作用域。 您的错误是由名为范围的内容引起的
在此之后,您可以简单地调用它们,然后解析、循环、保存它
python中的非静态函数示例如下:
下面是一个编写TK代码的更好方法的示例:
我用粗体字写了这个重要的单词,这样你就可以阅读更多关于这个的内容,而不仅仅是复制/粘贴
要阅读的主题:
敬礼
相关问题 更多 >
编程相关推荐