首页 > 解决方案 > 当特定窗口关闭时,如何关闭所有 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- 我将如何在单独的文件中使用它?

标签: pythonpython-3.xtkinterlogic

解决方案


我假设您的其他脚本有单独的实例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()


推荐阅读