python destroy函数_Python Tkinter,销毁顶层函数

作者分享了解决Tkinter中异步操作导致Toplevel窗口延迟显示的问题,通过在主线程中创建子线程执行耗时任务,并使用after函数定期检查任务完成状态。此外,还探讨了如何避免GUI冻结,以提供更流畅的用户体验。
摘要由CSDN通过智能技术生成

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

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

Thanks!

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值