在tkinter中关闭子窗口时如何关闭父窗口

时间:2020-03-29 23:05:04

标签: python user-interface authentication tkinter

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

1 个答案:

答案 0 :(得分:0)

您可以绑定到窗口上的<Destroy>事件。在bound函数中,您可以执行任何操作,包括销毁根窗口。

在下面的示例中,杀死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.widget是否为self的原因是由于绑定到根或顶层窗口的函数被该窗口内的所有子代自动继承的事实,您只想破坏根窗口当实际的顶层窗口被破坏时。