Reputation: 15098
I was writing code to show time every second and then noticed that eventually after some time(approx 30 seconds) time starts lagging behind the original time. I was able to reproduce the issue, so was someone I know. Hopefully you guys too can reproduce this.
Code:
from tkinter import *
import time
win = Tk()
win.geometry('400x400')
frame=Frame(win)
frame.grid()
labelTD=Label(frame)
labelTD.grid(row=2,column=0)
def countdown(n):
mn, secs =divmod(n, 60)
hr, mn = divmod(mn, 60)
labelCD.config(text=f"{hr:02}:{mn:02}:{secs:02}")
labelCD.config(font='infra 50 bold',foreground='black',background='white')
labelCD.grid(row=0)
if n >= 0:
labelCD.after(1000, countdown, n-1)
else:
labelCD.destroy()
def clock():
t=time.strftime('%A''\n''%D''\n''%I:%M:%S',time.localtime())
if t!='':
labelTD.config(text=t,font='infra 50 bold',foreground='black',background='white')
Hr = time.strftime('%H')
Mn = time.strftime('%M')
Sc = time.strftime('%S')
if int(Hr)==8 and int(Mn)==41 and int(Sc)==0: ### you can trigger it at any time you want
countdown(3600)
labelTD.after(1000,clock)
labelCD = Label(frame)
labelCD.grid()
clock()
win.mainloop()
Could this be due to usage of after()
or calling the function every second for a long time? If so, any alternatives to show timers? Thanks in advance :D
Upvotes: 0
Views: 218
Reputation: 385970
The after
method doesn't guarantee any sort of precision. The only guarantee it makes is that the function will be called some time after the requested timeout. It could be at 1000 ms, it could be at 1001, 1010, or something else. It depends on what else is going on in the system.
If you need something more accurate, you can save the current time in ms in your function, and do some math from the previous time your function ran, and then use that delta to adjust your calculations.
Upvotes: 1