如何在没有延迟的情况下循环刷新 Tkinter 显示

How to Refresh Tkinter Display on a Cycle with No Lag

我正在尝试创建一个简单的程序来监视显示在 Tkinter window 中并每秒刷新一次的数据。我目前使用的方法会在程序运行时在刷新周期中产生越来越大的滞后。

这是计数器形式的方法的超级简化表示。虽然循环以每个循环一秒的预期速率开始,但即使在几分钟后,循环时间也会明显变慢。任何消除这种滞后积累的建议将不胜感激。非常感谢!

from tkinter import *
i=0
root = Tk()
root.title("Simple Clock")
root.configure(background="black")

def Cycle():
    global i
    Label(root, text="------------------------", bg="black", fg="black").grid(row=0, column=0, sticky=W)
    Label(root, text = i, bg="black", fg="gray").grid(row=0, column=0, sticky=W)
    i += 1
    root.after(1000,Cycle)

root.after(1000,Cycle)    
root.mainloop()

停止在每次调用时创建新对象。相反,只更新发生变化的部分。对于上面的代码,它将更新第二个标签的文本:

from tkinter import *

def Cycle():
    global i
    labels[1]['text'] = i
    i += 1
    root.after(1000,Cycle)

i=0
root = Tk()
root.title("Simple Clock")
root.configure(background="black")
labels = list()
labels.append(Label(root, text="------------------------", bg="black", fg="black"))
labels.append(Label(root, bg="black", fg="gray"))
for j in range(len(labels)):
    labels[j].grid(row=0, column=0, sticky=W)
root.after(1000,Cycle)    
root.mainloop()