Home > Software design >  Clock with date and time in tkinter hangs
Clock with date and time in tkinter hangs

Time:06-19

I'm trying to create a clock with date and time but it hangs after some seconds. I want to know why it hangs and is not responding.

from tkinter import *
from tkinter.ttk import *
from time import strftime

root = Tk()
root.title('Clock')
root.config(bg='orange')


def time():
    string = strftime('%I:%M:%S %p ')
    string2 = strftime('%A  %d-%b-%Y')
    lbl.config(text=string)
    lbl.after(1000, time)
    lbl2.config(text=string2)
    lbl2.after(1000, time)

lbl = Label(root, font=('calibri', 50, 'bold'),
            background='orange',
            foreground='white')
lbl2 = Label(root, font=('calibri', 25, 'bold'),
            background='orange',
            foreground='white')

lbl.pack(anchor='center')
lbl2.pack(anchor='center')
time()

mainloop()

CodePudding user response:

You're calling after twice for each time time is called. So, you call it the first time and it puts two commands in the after queue. The first item in the queue is pulled off and runs, and it puts two more invocations in the queue. There are now three in the queue. The next invocation is pulled off of the queue so there are two remaining, but then it adds two so now there are four. It pulls one off but adds two so there are now five, then six, then seven, etc. Eventually, you can have hundreds or thousands queued up.

You need to call after only once inside of time so that you add one item on the queue each time you take one off.

def time():
    string = strftime('%I:%M:%S %p ')
    string2 = strftime('%A  %d-%b-%Y')
    lbl.config(text=string)
    lbl2.config(text=string2)
    lbl.after(1000, time)
  • Related