How do I create an automatically updating GUI using Tkinter?

You can use after() to run function after (for example) 1000 miliseconds (1 second) to do something and update text on labels. This function can run itself after 1000 miliseconds again (and again).

It is example with current time

from Tkinter import *
import datetime

root = Tk()

lab = Label(root)
lab.pack()

def clock():
    time = datetime.datetime.now().strftime("Time: %H:%M:%S")
    lab.config(text=time)
    #lab['text'] = time
    root.after(1000, clock) # run itself again after 1000 ms
    
# run first time
clock()

root.mainloop()

BTW: you could use StringVar as sundar nataraj Сундар suggested


EDIT: (2022.01.01)

Updated to Python 3 with other changes suggested by PEP 8 — Style Guide for Python Code

import tkinter as tk   # PEP8: `import *` is not preferred
import datetime

# --- functions ---
# PEP8: all functions before main code
# PEP8: `lower_case_name` for funcitons
# PEP8: verb as function's name
                     
def update_clock():
    # get current time as text
    current_time = datetime.datetime.now().strftime("Time: %H:%M:%S")
    
    # udpate text in Label
    lab.config(text=current_time)
    #lab['text'] = current_time
    
    # run itself again after 1000 ms
    root.after(1000, update_clock) 

# --- main ---

root = tk.Tk()

lab = tk.Label(root)
lab.pack()
    
# run first time at once
update_clock()

# run furst time after 1000ms (1s)
#root.after(1000, update_clock)

root.mainloop()

Leave a Comment