tkinter 自动关闭窗口
时间: 2023-07-13 10:12:32 浏览: 74
你可以使用`after`方法和`destroy`方法来实现定时自动关闭窗口的效果。具体实现步骤如下:
1. 在窗口初始化时,设置`after`方法,例如:`root.after(5000, root.destroy)`,表示在5000毫秒后执行`root.destroy()`方法。
2. 当需要手动关闭窗口时,需要取消`after`方法,可以使用`after_cancel`方法取消定时任务,例如:`root.after_cancel(task)`,其中`task`是`after`方法返回的任务ID。
下面是一个示例代码:
```
import tkinter as tk
root = tk.Tk()
# 设置定时关闭窗口任务
task = root.after(5000, root.destroy)
def cancel_task():
# 取消定时任务
root.after_cancel(task)
# 添加关闭按钮
btn_close = tk.Button(root, text="关闭", command=root.destroy)
btn_close.pack()
# 添加取消定时任务按钮
btn_cancel = tk.Button(root, text="取消定时任务", command=cancel_task)
btn_cancel.pack()
root.mainloop()
```
在上面的代码中,窗口会在5秒后自动关闭,也可以通过点击“关闭”按钮手动关闭窗口,同时也提供了一个“取消定时任务”按钮,点击该按钮可以取消定时任务。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)