将键盘事件绑定到 Tkinter child

Bind a keyboard event to a Tkinter child

我试图将关闭 window 函数绑定到 Tkinter child window。我已经能够为 parent 实施绑定过程,但我正在努力制定 child window.

的绑定实施

使用 中列出的示例,我尝试将关闭功能绑定到 Escape 键,但没有成功,也没有出现错误消息。

import tkinter as tk


def close(self):
    self.top.destroy()

class ChildWindow:
    def __init__(self, master):
        self.top = tk.Toplevel(master)
        self.frame = tk.Frame(self.top)
        self.frame.pack()

        self.frame.bind("<Escape>",lambda: close(self))        

        self.close_button = tk.Button(self.frame, text="Close", command=self.top.destroy)
        self.close_button.pack()

class MainWindow:
    def __init__(self, master):
        self.master = master
        self.frame = tk.Frame(self.master)

        self.about_button = tk.Button(self.frame, text="Open child window", command=self._open_child_window)
        self.about_button.pack()
        self.frame.pack()

    def _open_child_window(self):
        self.about_window = ChildWindow(self.master)

root = tk.Tk()
lf = MainWindow(root)
root.mainloop()

根据@stovfl 的建议,我将绑定更改为根的属性而不是 self.frame

这捕获了键盘事件并成功调用了close(self)函数。

import tkinter as tk

def close(self):
    self.top.destroy()

class ChildWindow:
    def __init__(self, master):
        self.top = tk.Toplevel(master)
        self.frame = tk.Frame(self.top)
        self.frame.pack()

        root.bind("<Escape>",lambda event: close(self))        

        self.close_button = tk.Button(self.frame, text="Close", command=self.top.destroy)
        self.close_button.pack()

    def close(self, event=None):
        print("destroy arg")
        self.root.destroy()


class MainWindow:
    def __init__(self, master):
        self.master = master
        self.frame = tk.Frame(self.master)



        self.about_button = tk.Button(self.frame, text="Open child window", command=self._open_child_window)
        self.about_button.pack()
        self.frame.pack()

    def _open_child_window(self):
        self.about_window = ChildWindow(self.master)

root = tk.Tk()
lf = MainWindow(root)
root.mainloop()