time.sleep() Equivalent on Tkinter

前端 未结 1 711
囚心锁ツ
囚心锁ツ 2021-01-21 21:09

I have to stop a loop and resume after many seconds. I tried to use after(), but the loop don\'t freeze. And when I use time.sleep() (works out tkinter), tkinter freeze. Have an

相关标签:
1条回答
  • 2021-01-21 21:54

    To create an analog of:

    for message in listOfMessages:
        time.sleep(message.time)
        change(message)
    

    in tkinter:

    def update_widget(app, messages):
        message = next(messages, None)
        if message is None: # end of the loop
            return
        delay = int(message.time * 1000) # milliseconds
        app.after(delay, change, message) # execute body
        app.after(delay, update_widget, app, messages) # next iteration
    
    update_widget(app, iter(listOfMessages))
    

    If you want to wait until change(message) finishes before continuing the loop:

    def iterate(message, app, messages):
        change(message)
        update_widget(app, messages)
    
    def update_widget(app, messages):
        message = next(messages, None)
        if message is None: # end of the loop
            return
        delay = int(message.time * 1000) # milliseconds
        app.after(delay, iterate, message, app, messages)
    
    update_widget(app, iter(listOfMessages))
    
    0 讨论(0)
提交回复
热议问题