Markas Povilaika
Markas Povilaika

Reputation: 67

How to insert a loop function into a label in Tkinter (self_updatable)

I have this loop that runs and changes x, how should I put it into a Tkinter label? Thanks in advance.

from tkinter import *
import time

root = Tk() 

def x_loop():
    x = 0
    while x <= 100:
        time.sleep(2)
        x = x + 1
        
l = Label(root, text = x_loop).pack(pady = 20)

root.mainloop()

Upvotes: 0

Views: 420

Answers (2)

TheLizzard
TheLizzard

Reputation: 7710

Instead of using StringVar as @Atlas435 did, you can use this simpler method:

import tkinter as tk

def x_loop():
    global x
    if x <= 100:
        x += 1
        # Update the label
        label.config(text=x)
        # after 2000 ms call `x_loop` again
        root.after(2000, x_loop)

x = 0
root = tk.Tk()

label = tk.Label(root, text=x)
label.pack(pady=20)

# STart the loop
x_loop()

root.mainloop()

Upvotes: 1

Thingamabobs
Thingamabobs

Reputation: 8082

Tkinter dosent like while loops, this is because a while loop dosent return to the mainloop till its finished and therefore you application isnt working during this time.

Tkinter provides for this the .after(*ms,*func) method and is used below. Also for changing the text of a tk.Label you can go for several ways. I think the best way is to use the inherated option textvariable.

The textvariable needs to be a tk.*Variable and configures the tk.Label as soon as the var is set.

Check out the working example below:

import tkinter as tk

x = 0
def change_text():
    global x
    var.set(x)
    x +=1
    root.after(100,change_text)#instead of a while loop that block the mainloop

root = tk.Tk()
var = tk.StringVar()
lab = tk.Label(root, textvariable=var)
lab.pack()
change_text()

root.mainloop()

Upvotes: 2

Related Questions