Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When I use update() with tkinter my Label writes another line instead of rewriting the same text

Tags:

python

tkinter

When I call the update() method using tkinter instead of rewriting the label it just writes the label under the previous call. I would like for this to rewrite over the previous line.

For Example:

root=Tk()
while True:
    w=Label(root, text = (price, time))
    w.pack()
    root.update()
like image 858
wDroter Avatar asked Sep 27 '11 17:09

wDroter


1 Answers

Your problem is simply this: when you do while True, you create an infinite loop. The code in that loop will run until you force the program to exit. In that loop you create a label. Thus, you will create an infinite number of labels.

If you want to update a label on a regular basis, take advantage of the already running infinite loop - the event loop. You can use after to schedule a function to be called in the future. That function can reschedule itself to run again, guaranteeing it will run until the program quits.

Here's a simple example:

import Tkinter as tk
import time

class SampleApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.clock = tk.Label(self, text="")
        self.clock.pack()

        # start the clock "ticking"
        self.update_clock()

    def update_clock(self):
        now = time.strftime("%H:%M:%S" , time.gmtime())
        self.clock.configure(text=now)
        # call this function again in one second
        self.after(1000, self.update_clock)

if __name__== "__main__":
    app = SampleApp()
    app.mainloop()
like image 143
Bryan Oakley Avatar answered Oct 05 '22 22:10

Bryan Oakley