3

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()

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

2 Comments

OH MY GOD THAT'S SO OBVIOUS. I am new to tkinter, not at all to python or to programming. Such a dumb mistake! Thanks. Although I'm surprised it didn't error on receiving NoneType for an argument....would have been informative and then I would have seen the mistake immediately.
@Aerovistae, According to after documentation, None is also a valid argument. (None is default value for callback parameter)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.