简体   繁体   English

一定时间后自动关闭窗口

[英]Automatically close window after a certain time

In a class, in a function I am creating a Tkinter Canvas. 在一个类中,在一个函数中,我正在创建一个Tkinter画布。 This function is being called by another class, I would like for the Tkinter window to pop up for 30 seconds and then close itself. 此函数正在由另一个类调用,我希望Tkinter窗口弹出30秒然后关闭自身。 I have it call 我有电话

master.mainloop()
time.sleep(30)
master.destroy() 

But I get an error 但我得到一个错误

"elf.tk.call('destroy', self._w) _tkinter.TclError: can't invoke "destroy" command: application has been destroyed" “ elf.tk.call('destroy',self._w)_tkinter.TclError:无法调用“ destroy”命令:应用程序已被破坏”

So how can I have it close itself? 那我怎么能自己关闭呢?

Don't use time.sleep() with tkinter. 不要在time.sleep()使用time.sleep() Instead, call the function after on the widget you want to close. 相反,调用函数after你要关闭的窗口小部件。

Here it is the most simple example: 这是最简单的示例:

import tkinter as tk

w = tk.Tk()
w.after(30000, lambda: w.destroy()) # Destroy the widget after 30 seconds
w.mainloop()

The problem here is that mainloop() does not return until the GUI has shut down. 这里的问题是,除非GUI关闭, mainloop()不会返回。

So, 30 seconds after the GUI has shut down and destroyed itself, you try to destroy it. 因此,在GUI关闭并销毁自身30秒 ,您尝试销毁它。 And obviously that fails. 显然这失败了。

But you can't just move the sleep and destroy calls inside the main loop, because if you sleep in the middle of the main loop, the GUI will freeze up. 但是您不能只在主循环内移动sleepdestroy调用,因为如果您sleep在main循环的中间,GUI将冻结。

So, you need some kind of timer that will not stop the main loop. 因此,您需要某种不会停止主循环的计时器。 tkinter includes the after method for exactly that purpose. 为此, tkinter包括了after方法。 This answer gives a detailed example of using it. 该答案给出了使用它的详细示例。

我正在设置一个新的服务器,以在tkinter窗口上发送按钮命令并打印消息。当ı按下按钮时,将在tkinter窗口上打印消息“ A”,而在ı释放按钮时,消息“ B”将显示在tkinter窗口中。直到再次按下该按钮为止。我希望消息在tkinter窗口上连续更改,但是ı只要按下按钮,我都不知道如何将tkinter窗口保持在屏幕上。您能帮我吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM