如何在 tkinter 中每小时刷新一次函数?

How to refresh a function every hour in tkinter?

我正在尝试制作一个简单的程序,从 API 获取信息并使用 tkinter 在 python GUI 上显示它。 到目前为止,我已经能够做到这一点,但新的挑战是让从 API 收集的信息每小时刷新一次。 基本上我需要 data() 函数每小时重新 运行 以便 GUI 上的信息更新。

from tkinter import *
import requests

def data():
    url = requests.get("https://stats.foldingathome.org/api/donor/PointofHorizon")
    json = str((url.json()))

    i = json.count(',')
    data = json.split(",")

    score = data[i]
    score = score.replace(" 'credit': ","")
    score = score.replace("}","")

    unit = data[0]
    unit = unit.replace("{'wus': ","")

    scores = Label(app, text = score)
    units = Label(app, text =  unit)

    scores.pack()
    units.pack()    

app = Tk()
app.geometry("500x200")
title = Label(app,text = "Folding Score")
title.pack()

我环顾四周,未能找到适合我的方法,如果有人能为我指出正确的方向,那就太好了。我还在学习。

我想你要找的是 tkinter 中的 after 方法。我更改了 data 函数以刷新小部件上的数据。我将创建标签的代码移到了 refresh_data 函数之外。创建小部件后,我调用 refresh_data 函数将信息放在小部件上。此函数将告诉 tkinter 在 运行 再次创建循环之前等待一个小时。

from tkinter import *
import requests

def refresh_data():
    url = requests.get("https://stats.foldingathome.org/api/donor/PointofHorizon")
    json = str((url.json()))

    i = json.count(',')
    data = json.split(",")

    score = data[i]
    score = score.replace(" 'credit': ","")
    score = score.replace("}","")

    unit = data[0]
    unit = unit.replace("{'wus': ","")

    scores.config(text=score)
    units.config(text=unit)

    app.after(3600000, refresh_data) #3600000 milliseconds in an hour

app = Tk()
app.geometry("500x200")
title = Label(app,text = "Folding Score")
title.pack()

scores = Label(app)
units = Label(app)


scores.pack()
units.pack()

refresh_data()

app.mainloop()