首页 > 解决方案 > 在tkinter中关闭子窗口时如何关闭父窗口

问题描述

我正在制作一个 GUI,并在其中隐藏根目录。因此,当我关闭使用 x 箭头显示的窗口时,我不会让整个程序结束,而不仅仅是可以看到的窗口。因为否则用户在关闭程序时会遇到问题。我的根是隐藏的,
可以看到登录,
当使用顶部的红色 x 关闭登录时,我也想关闭根该怎么做?

标签: pythonuser-interfaceauthenticationtkinter

解决方案


您可以绑定到<Destroy>窗口上的事件。在绑定函数中,您可以做任何您想做的事情,包括销毁根窗口。

在下面的示例中,杀死Toplevel窗口将破坏根窗口。

import tkinter as tk

class Window(tk.Toplevel):
    def __init__(self, root, label):
        super().__init__(root)
        self.root = root
        label = tk.Label(self, text=label)
        label.pack(padx=20, pady=20)

        self.bind("<Destroy>", self.kill_root)

    def kill_root(self, event):
        if event.widget == self and self.root.winfo_exists():
            self.root.destroy()

root = tk.Tk()
label = tk.Label(root, text="Root window")
label.pack(padx=20, pady=20)

w1 = Window(root, "This is a toplevel window")

root.mainloop()

检查的原因event.widgetself由于绑定到根窗口或顶层窗口的函数会被该窗口内的所有子窗口自动继承。您只想在实际顶层窗口被销毁时销毁根窗口。


推荐阅读