Reputation: 13
I'm trying to create a simple program to monitor data that displays in a Tkinter window and refreshes itself every second. The method I'm currently using creates an ever-increasing lag in the refresh cycle as the program runs.
This is a super simplified representation of the approach in the form of a counter. While the cycle begins at the intended rate of one second per loop, even after just a few minutes the cycle-time becomes noticeably slower. Any suggestions to eliminate this lag accumulation would be greatly appreciated. Thanks so much!
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()
Upvotes: 1
Views: 459
Reputation: 15345
Stop creating new objects with each call. Instead, only update the parts that change. For the code above it would be updating the 2nd Label's text:
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()
Upvotes: 1