python - 当特定窗口关闭时,如何关闭所有 Tkinter 窗口?
问题描述
我在 Python Tkinter 中有这个应用程序。有一个 Python 文件,它是一个主菜单。Toplevel
当我单击主菜单中的一个选项时,它会导入一个 python 文件,其中包含创建一个新窗口的代码(由于某些原因不能用于新窗口)。所以当我关闭主菜单时,它应该关闭所有其他窗口。
这是我的主菜单代码:
from tkinter import *
root = Tk()
root.geometry("600x600")
def newWindowImport():
import file1
def newWindowImport2():
import file2
newWindow = Button(text="new window", command=newWindowImport).pack()
newWindow2 = Button(text="new window", command=newWindowImport2).pack()
# Here is there a way so that when I exit it destroys the Main Menu as well as the opened windows
exitBtn = Button(text="Exit", command=root.destroy())
root.mainloop()
我尝试了该root.destroy
方法,但它只破坏了主菜单,而不是所有的窗口。有没有办法让我退出主菜单时它会破坏主菜单以及打开的窗口?如果我要使用Toplevel
- 我将如何在单独的文件中使用它?
解决方案
我假设您的其他脚本有单独的实例Tk()
,它们自己的mainloop()
并且不在函数下,如果是这种情况,您可以将文件中的所有代码放在函数下并使用Toplevel()
,例如,file1
应该看起来像
def something():
window=Toplevel()
#Rest of the code
同样file2
,在你的主程序中你可以做这样的事情
from tkinter import *
import file1, file2
root = Tk()
root.geometry("600x600")
def newWindowImport():
file1.something()
def newWindowImport2():
file2.something()
newWindow = Button(text="new window", command=newWindowImport)
newWindow.pack()
newWindow2 = Button(text="new window", command=newWindowImport2)
newWindow2.pack()
# Here is there a way so that when I exit it destroys the Main Menu as well as the opened windows
exitBtn = Button(text="Exit", command=root.destroy)
root.mainloop()
您也可以放弃这些功能并进行这些更改以使其更短
newWindow = Button(text="new window", command=file1.something)
newWindow.pack()
newWindow2 = Button(text="new window", command=file2.something)
newWindow2.pack()
您的方法不起作用的原因是每个文件都有自己的文件,因此当您调用主代码mainloop()
时它们无法被销毁。root.destroy
另请注意,我已从 the 中删除了括号()
,command=root.destroy
否则将在程序初始化后立即调用它。
编辑:正如@martineau 在评论中所建议的那样,最好单独.pack()
在Button
实例上使用,因为它在程序稍后使用实例时提供了更大的灵活性,而不是让它们保持作为None
返回值的值.pack()
推荐阅读
- google-oauth - 如何使用 CDAP http 插件通过 OAUTH 2.0 获取 google cloud api?
- java - 如何使我的代码成为同步 POST volley 请求?
- python - Telegram Bot SendDocument pdf
- c - 使用单指针访问结构元素?
- dart - 在 Dart for-in 循环中使用“final”或“var”?
- unity3d - 统一动态绘制自由二维形状
- java - 回文递归算法的时间复杂度
- python - 为什么我的 Numpy 掩码不适用于 OpenCV bitwiseAnd()?
- python - 如果列下该行中的任何单元格不是浮点数,如何删除数据框中的行?
- python - Flask 网页 - 需要显示用户列表并允许管理员选择多个条目