charles M
charles M

Reputation: 75

Tkinter Update intvar in label

I am trying to have an integer to constantly change inside a label using Tkinter.

import tkinter
root = tkinter.Tk()
var  = tkinter.IntVar()

label  = tkinter.Label(root, textvariable=var)
button = tkinter.Button(root, command=lambda: var.set(var.get() + 1), text='+1')

label.pack()
button.pack()
root.mainloop()

The closest I have come to what I need after searching is to the example above. However you need to click a button for the integer to change, What I need is without anything for the user to do, for the integer to change.

I have an array which is constantly getting bigger while the program is running which I need to print its length each time there is one new element appended to it.

Update: Working answer:

import tkinter
import time
root = tkinter.Tk()
var  = tkinter.IntVar()

label  = tkinter.Label(root, textvariable=var)
label.pack()
def update_Value():
    for i in range(5):
        time.sleep(1)
        var.set(i)
        root.update()
root.after(0, update_Value)
root.mainloop()

Upvotes: 0

Views: 5229

Answers (1)

furas
furas

Reputation: 143231

You can use root.after(time_in_milisecond, function_name) to call function which change value in label without user interaction.

Example: showing current time using after


Here's an example of the code from the question, using after to automatically call the function after mainloop starts:

import tkinter
import time
root = tkinter.Tk()
var  = tkinter.IntVar()

label  = tkinter.Label(root, textvariable=var)
label.pack()

def function():
    for i in range(5):
        var.set(i)
        root.update()
        time.sleep(1) # to slow down

root.after(1, function)

root.mainloop()

Upvotes: 1

Related Questions