gpt4 book ai didi

python - Tkinter 与 openweather

转载 作者:行者123 更新时间:2023-11-30 21:53:41 26 4
gpt4 key购买 nike

我尝试在 Tkinter 中创建一个下拉框。我希望每次我选择一个国家并单击左侧按钮时,它都会显示我选择的国家的天气。显然,我必须手动更改这行代码(在定义天气函数中)weather_status = output['list'][2]['sys'] 每次我想了解该国的天气。如何在无需手动更改该行代码的情况下获取该国家/地区的天气?

import requests
import tkinter as tk
from tkinter import Tk, BOTH, Menu, StringVar, messagebox, Label

def weather():
city = city_list.get()
url = 'http://api.openweathermap.org/data/2.5/group?id=1880252,524901,703448,2643743&units=metric&appid=de9880142c6480331da965bf187a4b6e'.format(city)
req = requests.get(url)
output = req.json()
weather_status = output['list'][2]['sys']
weather_status_label.configure(text = 'weather status: ' + str(weather_status))

window = tk.Tk()
window.geometry('400x350')

## adding a drop box
OptionList= [
'Singapore',
'London',
'Bangkok',
'Moscow'
]
city_list = StringVar(window, OptionList)
city_list.set('select the city')
opt = tk.OptionMenu(window, city_list, *OptionList)
opt.config(width = 90, font = ('Arial', 12))
opt.pack()

## adding a label on top
lbl = tk.Label(window, text = 'Select your city', bg = 'light green')
lbl.pack()

## adding buttons
def win_quit():
if messagebox.askokcancel('quit','Do you want to quit?'):
window.destroy()

button_1 = tk.Button(window, text = 'Quit', height = 2,
width = 4, command = win_quit, activeforeground = 'red',
relief = 'ridge')
button_1.place(x= 300, y= 60)

button_2 = tk.Button(window, text = 'Click', height = 2,
width = 4, command = weather, activeforeground = 'green',
relief = 'ridge')
button_2.place(x= 70, y= 60)

## adding another label

weather_status_label = Label(window, font=('Arial', 10,'bold' ))
weather_status_label.pack(padx= 10, pady= 60)

window.mainloop()

enter image description here

最佳答案

如果我理解了您的问题,您可以通过“跟踪”名为 city_listStringVar 的更改并让它调用 weather() 每次其值更改时都会起作用。

文档The Variable Classes (BooleanVar, DoubleVar, IntVar, StringVar)中描述了跟踪.

这样您就不必更改 weather() 中的 weather_status = output['list'][2]['sys'] 语句> 函数,您可以让它引用您已有的当前 city 值:

def weather():
city = city_list.get()
url = 'http://api.openweathermap.org/data/2.5/group?id=1880252,524901,703448,2643743&units=metric&appid=de9880142c6480331da965bf187a4b6e'.format(city)
req = requests.get(url)
output = req.json()

# weather_status = output['list'][2]['sys'] # CHANGED.
weather_status = city

weather_status_label.configure(text = 'weather status: ' + str(weather_status))

然后添加代码以通过调用其修改版本来进行跟踪:

...
## adding a drop box
OptionList= [
'Singapore',
'London',
'Bangkok',
'Moscow'
]
city_list = StringVar(window, OptionList)
city_list.set('select the city')

observer = city_list.trace('w', lambda *_: weather()) # ADDED.

opt = tk.OptionMenu(window, city_list, *OptionList)
opt.config(width = 90, font = ('Arial', 12))
opt.pack()
...

关于python - Tkinter 与 openweather,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59580138/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com