# How do I create an automatically updating GUI using Tkinter in Python?

PythonServer Side ProgrammingProgramming

GUI window has many controls such as labels, buttons, text boxes, etc. We may sometimes want the content of our controls such as labels to update automatically while we are viewing the window.

We can use after() to run a function after a certain time. For example, 1000 milliseconds mean 1 second. The function which we call continuously after a certain amount of time will update the text or any updation you want to happen.

We have a label on our window. We want the text of the label to update automatically after 1 second. To keep the example easy, suppose we want the label to show some number between 0 and 1000. We want this number to change after each 1 second.

We can do this by defining a function that will change the text of the label to some random number between 0 and 1000. We can call this function continuously after an interval of 1 second using the after().

## Example

from Tkinter import *
from random import randint
root = Tk()
lab = Label(root)
lab.pack()

def update():
lab['text'] = randint(0,1000)
root.after(1000, update) # run itself again after 1000 ms

# run first time
update()

root.mainloop()

This will automatically change the text of the label to some new number after 1000 milliseconds. You can change the time interval according to need. The update function can be modified to perform the required updation.

### root.after(1000,update)

This line of the code performs the main function of recalling the function update().

The first parameter in root.after() specifies the time interval in milliseconds after which you want the function to be recalled.

The second parameter specifies the name of the function to be recalled.

Published on 11-Mar-2021 14:12:54