简体   繁体   English

Tkinter:经过一定时间后如何更新标签文本?

[英]Tkinter: How to update a label text after a certain amount of time has passed?

So, I'm trying to create a basic Tkinter program which, when I press a button, updates the text on a label field, waits X amount of seconds and then update the label again. 因此,我试图创建一个基本的Tkinter程序,当我按下一个按钮时,该程序将更新标签字段上的文本,等待X秒钟,然后再次更新标签。

For example: 例如:

I click the button, the label clears immediately after pressing it, then the program waits 3 seconds and shows "Hello" on screen. 我单击按钮,按下按钮后标签立即清除,然后程序等待3秒钟并在屏幕上显示“ Hello”。

The code shown below does not do what I want it to do because when I press the button, it remains pressed for X amount of time and then the text is updated inmediately. 下面显示的代码无法实现我想要的功能,因为当我按下按钮时,它将保持按下状态X倍的时间,然后立即进行文本更新。 I want to press the button, clear the label, wait for 3 seconds and then show "Hello" on screen. 我要按下按钮,清除标签,等待3秒钟,然后在屏幕上显示“ Hello”。

from tkinter import *

 class Origin:

    def __init__(self):

        self.root = Tk()
        self.root.geometry('800x600')
        self.root.config(bg="black")

        self.v = StringVar()
        self.v.set('O  R  I  G  I  N')

        self.main_label = Label(self.root, textvariable=self.v, font="Arial 40", fg="white", bg="black")
        self.main_label.place(x=240, y=150)

        self.clear = Button(self.root, text='Clear', command=self.clear)
        self.clear.place(x=400, y=400)

        self.root.mainloop()

    def clear(self):
        #just to clear the string
        self.v.set('')

        self.root.after(3000, self.v.set('Hello'))


 def main():
    App = Origin()

 if __name__ == '__main__':
    main()

after needs callback - it means function's name without () and arguments. after需要callback -这意味着不带()和参数的函数名称。 If you have to use function with argument then use `lambda 如果必须使用带参数的函数,则使用`lambda

after(3000, lambda:self.v.set('Hello'))

or create function which doesn't need arguments 或创建不需要参数的函数

def callback():
    self.v.set('Hello')

self.root.after(3000, callback)

Your current code works like 您当前的代码如下

result = self.v.set('Hello')
self.root.after(3000, result)

It executes function self.v.set('Hello') at once and uses its result as callback in after() . 它立即执行self.v.set('Hello')函数,并将其结果用作after() callback


EDIT: as @acw1668 said in comment you can also run function with arguments this way 编辑:正如@ acw1668在评论中所说,您也可以通过这种方式运行带有参数的函数

self.root.after(3000, self.v.set, 'Hello')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM