Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python tkinter : loop in Label

Hello I just wanted that the Label change/refresh during the loop, but it doesn't work

This my code

fen1 = Tk()

v = StringVar()
Label(fen1,textvariable=v).pack()

i=0

while(1):
    i=i+1
    v.set(i)
fen1.mainloop() 

Thanks

like image 965
user1497451 Avatar asked Jan 20 '26 21:01

user1497451


1 Answers

here, try this:

from Tkinter import *
import time
root=Tk()

variable=StringVar()

def update_label():
    i=0
    while 1:
        i=i+1
        variable.set(str(i))
        root.update()

your_label=Label(root,textvariable=variable)
your_label.pack()
start_button=Button(root,text="start",command=update_label)
start_button.pack()
root.mainloop()

That should give you a good example. However, it is important to note that during the while loop, you MUST call root.update() otherwise your GUI will freeze until the loop completes (in this case it never does) and never show your numbers.

Also note that you can call update_label() from anywhere in your program. I just added it to the start button for example purposes.

What was wrong with your code was that you had set the while loop free-floating and most importantly before your GUI's mainloop. When you do this, since this loop is infinate, it never allows Tkinter to start its mainloop(). However, if you were to put the while loop after the mainloop, then that would never be executed until after you exit the GUI, this is because the mainloop is infinate until it is stopped (closing the GUI).

So to fix this you simply put it in a function and call it later on during Tkinter's mainloop. You can do this various ways as well, for example, you can use .after() to perform a specific task after a certain amount of time, or make it the command of a button to be run when pressed, ect., ect. .

However, The proper code you should use is the following, as you do not really want infinate loops in your code (other then you mainloop).:

class App (object):
    def __init__(self):
        self.root=Tk()
        self.variable=StringVar()
        self.i=0
        self.your_label=Label(self.root,textvariable=self.variable)
    def grid(self):
        self.your_label.pack()
    def update_label(self):
        self.i=self.i+1
        self.variable.set(str(self.i))
        self.root.after(20,self.update_label)
    def run(self):
        self.grid()
        self.root.after(20,self.update_label)
        self.root.mainloop()

if __name__=='__main__':
    App().run()
like image 98
IT Ninja Avatar answered Jan 22 '26 12:01

IT Ninja



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!