使用tkinter的update()时,Label显示新行而不是重写相同的文本

11 投票
5 回答
70832 浏览
提问于 2025-04-17 03:12

当我使用tkinter调用update()方法时,它并不是覆盖之前的标签,而是把新的标签写在了之前标签的下面。我希望它能覆盖掉之前的那一行。

举个例子:

root=Tk()
while True:
    w=Label(root, text = (price, time))
    w.pack()
    root.update()

5 个回答

3

你应该使用 .configure 来代替。

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

不。

我猜,虽然我没看到代码,但wDroter写的代码里至少有几个地方可能让人困惑。一般来说,在结构良好的Tkinter代码中,根本不需要使用update()这个方法。下面有一个小例子,展示了如何更新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()

运行这个代码。点击按钮。每次你点击(只要间隔至少一秒),你会看到文本会更新。

18

你的问题很简单:当你写 while True 时,你就创建了一个无限循环。这个循环里的代码会一直运行,直到你强制让程序退出。在这个循环里,你 创建 了一个标签。因此,你会创建出无数个标签。

如果你想定期更新一个标签,可以利用已经在运行的无限循环,也就是事件循环。你可以使用 after 来安排一个函数在未来某个时间被调用。这个函数可以自己重新安排,再次运行,确保它会一直运行,直到程序退出。

下面是一个简单的例子:

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

撰写回答