Python Tkinter,销毁顶层函数 [英] Python Tkinter, destroy toplevel after function

查看:239
本文介绍了Python Tkinter,销毁顶层函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Tkinter作为GUI使用python编程某些驱动器.当我的机器运行时,我想向用户显示一个顶层窗口,其中包含一些信息,这些信息应在功能完成后自行关闭.这是我的最小示例:

I'm programming some drives with python using Tkinter as GUI. When my machine is running, I'd like to show the user a toplevel window with some information which should close itself after the function completes. This is my minimal example:

from Tkinter import *
import time


def button_1():
     window = Toplevel()
     window.title("info")
     msg = Message(window, text='running...', width=200)
     msg.pack()     
     time.sleep(5.0)
     window.destroy()

master = Tk()
frame = Frame(width=500,height=300)
frame.grid()
button_one = Button(frame, text ="Button 1", command = button_1)
button_one.grid(row = 0, column = 0, sticky = W + E)
mainloop()

主要问题是,仅在5秒结束后才出现顶级窗口.有什么建议? 谢谢!

The main problem is, that the toplevel window just appears after 5 seconds are over. Any suggestions? Thanks!

推荐答案

time.sleep(5)在GUI有时间更新之前启动,这就是为什么仅在5秒钟结束后才显示顶层的原因.若要更正此问题,可以在time.sleep(5)之前添加window.update_idletasks()以强制更新显示.

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.

但是,正如Bryan Oakley在他的答案中指出的那样,在执行time.sleep(5)时,GUI被冻结.我想您的最终目标不是执行time.sleep而是一些耗时的操作.因此,如果您不想冻结GUI但不知道执行将花费多长时间,则可以在单独的线程中执行功能,并定期使用after:

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()

这篇关于Python Tkinter,销毁顶层函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆