开发者

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

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=T开发者_Go百科k()
while True:
    w=Label(root, text = (price, time))
    w.pack()
    root.update()


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


No.

I suspect, without having seen it, that there are at least a couple of confusions in the code wDroter has written. In general, it is NOT necessary in well-structured Tkinter code to use update() at all. Here's a small example that illustrates updates to the text of a Label:

import Tkinter
import time

def update_the_label():
    updated_text = time.strftime("The GM time now is %H:%M:%S.", time.gmtime())
    w.configure(text = updated_text)

root = Tkinter.Tk()
w = Tkinter.Label(root, text = "Hello, world!")
b = Tkinter.Button(root, text = "Update the label", command = update_the_label)
w.pack()
b.pack()

root.mainloop()

Run this. Push the button. Each time you do so (as long as your pushes differ by at least a second), you'll see the text update.


you want to use .configure insted

while True:
    w.Configure(text = (price, time))
    root.update()


instead of w.pack() you can write w.grid(row=0, column=0)

pack() in tkinter usually packs things in a single row/column. It lays things out along the sides of a box. Whereas, grid() has more of a table like structure. So when you write row=0 and column=0, it has no choice but to replace the previous if it exists. Because you have provided a very specific position instead of just pushing it to the window (which is hat pack() does)


The BadRoot class should demonstrate the problem that you are having. You can comment out the call to the class to verify with a complete, working example. If you run the code as written, it will update the label in the GoodRoot class. The first line that is commented out shows an alternative syntax for changing the text in your label.

from tkinter import Tk, Label
from time import sleep
from random import random

class BadRoot(Tk):

    def __init__(self, price, time):
        super().__init__()
        self.labels = []
        while True:
            self.labels.append(Label(self, text=(price, time)))
            self.labels[-1].pack()
            self.update()
            sleep(1)

class GoodRoot(Tk):

    def __init__(self, callback):
        super().__init__()
        self.label = Label(self, text=str(callback()))
        self.label.pack()
        while True:
##            self.label['text'] = str(callback())
            self.label.configure(text=str(callback()))
            self.update()
            sleep(1)

if __name__ == '__main__':
##    BadRoot('$1.38', '2:37 PM')
    GoodRoot(random)

The problem with your original code is that a new label is created and packed into the interface each time through the loop. What you actually want to do is just edit the text being displayed by the label instead replacing the label with a new one. There are others ways of doing this, but this method should work for you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜