【发布时间】:2021-05-27 05:21:30
【问题描述】:
情况:我有一个 tkinter GUI,可以显示从 API 收集的天气数据。我有一个从 API 请求数据的“get_weather”函数。响应通过管道传输到“格式化”函数,然后返回到“get_weather”函数。然后将格式化的字符串显示为 tkinter 标签的文本。该程序旨在在启动时运行(cronjob)并保持连续运行。一切都很好,除了...
问题:我无法让“get_weather”功能自动刷新。我希望“get_weather”函数每 30 分钟运行一次,以将数据从 API 更新到 GUI。
我试过了:一个无限的While循环;这会阻止 Tk 循环启动。在代码中加入 time.sleep(60);停止 GUI 启动一分钟。和 after 方法(请参阅下面的用法)。除非我将时间参数设为一个巨大的数字,否则它似乎没有做任何事情。然后它延迟了 GUI 的启动。
附带说明:我没有自己上课。这是下一次迭代的计划。我只是没有信心上课。在我这样做之前,我想解决其他问题。此外,我在 Tk 循环开始时定义了所有函数。它们在循环中被调用。这对我来说很有意义,但如果有人有理由让他们参与进来,我想听听。我已经学会了线程,但我认为这不是解决方案。
代码如下:(程序300行,还有其他功能,我只是把问题代码总结一下)
from Tkinter import Tk*
import [a few other modules]
def change_location(city):
# passes a 'city' value from an Entry widget
# sends request to a geo location api for gps coordinates.
# saves location coordinates to a local config file.
getweather()
def formatting(json):
# takes json from api and formats it to a string
return string
def get_weather():
# opens a local config file with gps coordinates.
# Note: the weather api I'm using requires gps coordinates
# uses gps coordinates in weather api request
weather['text'] = formatting(response.json())
# start of tkinter loop
root = Tk()
weather = Label(root)
# manual refresh button that works
refresh = Button(root, text="Refresh", command=get_weather)
new_city = Entry(root)
weather.grid(row=0, column=0)
refresh.grid(row=0, column=1)
new_city.grid(row2, column=1)
# after method like his only seems to delay GUI launch only calls 'get_weather' once.
# I also tried weather.after(10000, get_weather())
root.after(10000, get_weather)
root.mainloop()
我可以发布完整的代码,但我认为没有人愿意通读 300 行代码来寻找一个简单的解决方案。
编辑:更正按钮命名错误 + 添加 'change_location' 功能到summery
【问题讨论】:
标签: python loops tkinter nested-loops