Reputation: 55
I been working on a simple Tkinter Gui in which a timer gets involved. The thing is that the timer goes faster than the milliseconds specified in the .after()
method. Here is my code:
import tkinter
import time
from tkinter import *
seconds = 604800
FONT = ("Arial", 24)
window = tkinter.Tk()
window.attributes('-topmost', True)
window.attributes('-fullscreen', True)
window.title("Sandbox Crypto")
window.configure(bg='red')
seconds = 604800
def gui():
text = StringVar()
def substract_seconds():
global seconds
seconds -=1
while seconds > 0:
mins, secs = divmod(seconds, 60)
hours, mins = divmod(mins, 60)
days, hours = divmod(hours, 24)
timer = '{:02d}:{:02d}:{:02d}:{:02d}'.format(days,hours,mins, secs)
text.set(timer)
Time_label = Label(window, textvariable=text, bg='red', fg='white', font=FONT)
Time_label.grid()
Time_label.place(x=10, y=300)
Time_label.update()
Time_label.after(1000, substract_seconds)
window.mainloop()
gui()
The strange thing here is that i investigated the .after()
method common errors and most of them were related to the method actually going slower than it should. One of my theories is that is an error related to the CPU speed because the speed of the clock varies through the time. What I infer from this is that sometimes it goes faster and then it slows down and continue going faster.
Upvotes: 0
Views: 633
Reputation: 47193
Since you used while loop, there is new scheduled task created to update the seconds
in every iteration.
You don't need the while loop at all, below is modified gui()
:
def gui():
text = StringVar()
Time_label = Label(window, textvariable=text, bg='red', fg='white', font=FONT)
Time_label.place(x=10, y=300)
def countdown(seconds=seconds):
mins, secs = divmod(seconds, 60)
hours, mins = divmod(mins, 60)
days, hours = divmod(hours, 24)
timer = '{:02d}:{:02d}:{:02d}:{:02d}'.format(days,hours,mins, secs)
text.set(timer)
if seconds > 0:
Time_label.after(1000, countdown, seconds-1)
countdown() # start the count down
window.mainloop()
Upvotes: 2