Python Tkinter, destroy toplevel after function

徘徊边缘 提交于 2019-12-06 02:57:53

time.sleep(5) is launched before the GUI has time to update, that's why the toplevel only appears after the 5 seconds are over. To correct this, you can add window.update_idletasks() before time.sleep(5) to force the update the display.

But, as Bryan Oakley points out in his answer, the GUI is frozen while time.sleep(5) is executed. I guess that your ultimate goal is not to execute time.sleep but some time consuming operation. So, if you do not want to freeze the GUI but do not know how long the execution will take, you can execute your function in a separated thread and check regularly whether it is finished using after:

import Tkinter as tk
import time
import multiprocessing

def function():
    time.sleep(5)


def button_1():
    window = tk.Toplevel(master)
    window.title("info")
    msg = tk.Message(window, text='running...', width=200)
    msg.pack()
    thread = multiprocessing.Process(target=function)
    thread.start()
    window.after(1000, check_if_running, thread, window)


def check_if_running(thread, window):
    """Check every second if the function is finished."""
    if thread.is_alive():
        window.after(1000, check_if_running, thread, window)
    else:
        window.destroy()


master = tk.Tk()
frame = tk.Frame(width=500,height=300)
frame.grid()
button_one = tk.Button(frame, text ="Launch", command=button_1)
button_one.grid(row = 0, column = 0, sticky = "we")
master.mainloop()

A general rule of thumb is that you should never call sleep in the thread that the GUI is running in. The reason is that sleep does exactly what it says, it puts the whole program to sleep. That means that it is unable to refresh the window or react to any events.

If you want to do something after a period of time, the correct way to do that is with after. For example, this will destroy the window after five seconds:

window.after(5000, window.destroy)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!