简体   繁体   中英

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.

For example:

I click the button, the label clears immediately after pressing it, then the program waits 3 seconds and shows "Hello" on screen.

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. I want to press the button, clear the label, wait for 3 seconds and then show "Hello" on screen.

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. If you have to use function with argument then use `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() .


EDIT: as @acw1668 said in comment you can also run function with arguments this way

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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