简体   繁体   中英

Python Tkinter Label Delay

This maybe a silly question to ask. I have a label in Tkinter GUI and i want it to be updated through time.

Example:

Msglabel=Tkinter.Label(... text="")

Msglabel.Cofigure(text=" EXAMPLE!")

Wait(5sec)

Msglabel.Configure(text=" NEW EXAMPLE!")

I've read about the after() method but im looking for something like Wait.

You'll need to hand over control to Tkinter during your wait period since Tkinter updates the UI in a single threaded loop.

Sleeping between the configure calls will hang the UI.

As you mentioned, after is the method you want. Try something like this:

try:
    import Tkinter as tkinter  # Python 2
except ImportError:
    import tkinter  # Python 3
import itertools


class MyApplication(object):
    def __init__(self):
        # Create and pack widgets
        self.root = tkinter.Tk()
        self.label = tkinter.Label(self.root)
        self.button = tkinter.Button(self.root)
        self.label.pack(expand=True)
        self.button.pack()

        self.label['text'] = 'Initial'
        self.button['text'] = 'Update Label'
        self.button['command'] = self.wait_update_label

        # Configure label values
        self.label_values = itertools.cycle(['Hello', 'World'])

    def launch(self):
        self.root.mainloop()

    def wait_update_label(self):
        def update_label():
            value = next(self.label_values)
            self.label['text'] = value

        update_period_in_ms = 1500
        self.root.after(update_period_in_ms, update_label)
        self.label['text'] = 'Waiting...'


if __name__ == '__main__':
    app = MyApplication()
    app.launch()

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