Question

I'm creating a single StringVar called time_display, which contains a string of the fashion 3:14:02, and a single label in the window which should (in theory) reflect updates to said StringVar. However, when I call updateTime to check the time and update it, I crash in an infinite loop. Other adjustments I have made have resulted in no infinite loop but no updating clock either. What am I doing wrong?

from tkinter import *
from tkinter import ttk
import time

root = Tk()
root.title("Clock")

def updateTime(var):
    hours = time.localtime().tm_hour
    if hours == 0:
        hours = 12
    minutes = time.localtime().tm_min
    if minutes < 10:
        minutes = '0' + str(minutes)
    else:
        minutes = str(minutes)
    seconds = time.localtime().tm_sec
    if seconds < 10:
        seconds = '0' + str(seconds)
    else:
        seconds = str(seconds)
    current_time = str(hours) + ':' + minutes + ':' + seconds
    var.set(current_time)
    root.after(500, updateTime(var))

time_display = StringVar()
updateTime(time_display)

ttk.Label(root, textvariable=time_display).grid(column=0, row=0)
root.mainloop()
Was it helpful?

Solution

In following line, the code is calling updateTime directly; causing recursive call.

root.after(500, updateTime(var))
#                         ^   ^

Pass the function and argument without calling it will solve your problem.

root.after(500, updateTime, var)

Alternatively you can use lambda:

root.after(500, lambda: updateTime(var))

BTW, using time.strftime, updateTime can be reduced:

def updateTime(var):
    var.set(time.strftime('%H:%M:%S'))
    root.after(500, updateTime, var)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top