0

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

2 Answers2

2

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()
Thingamabobs
  • 7,274
  • 5
  • 21
  • 54
  • 1
    It's much easer to just use `lab.config(text=)` – TheLizzard Apr 18 '21 at 09:41
  • 1
    @MarkasPovilaika ~ Consider marking this as the correct answer if this answered your question correctly. Click [here](https://meta.stackexchange.com/a/5235/775796) to learn how :D – Delrius Euphoria Apr 18 '21 at 09:43
  • @TheLizzard thanks. Could you show a fully working example with the easier method? – Markas Povilaika Apr 18 '21 at 09:44
  • @Atlas435 i am trying to pack lab with a x and y variable "lab = tk.Label(root, textvariable = var).pack(x=10,y=10)", however I get this error: _tkinter.TclError: bad option "-x": must be -after, -anchor, -before, -expand, -fill, -in, -ipadx, -ipady, -padx, -pady, or -side. Is there solution for that? – Markas Povilaika Apr 18 '21 at 11:59
  • `.pack()` dosent uses *x* and *y* coordinates, `.place()` do. [Check out, for more](https://stackoverflow.com/questions/63536505/how-do-i-organize-my-tkinter-appllication/63536506#63536506) – Thingamabobs Apr 18 '21 at 12:01
1

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()
TheLizzard
  • 7,248
  • 2
  • 11
  • 31