如何从该小部件获取放置小部件的根 window?

How to get the root window where a widget is placed from that widget?

我正在创建一个基于 Tkinter 的 GUI。我创建了一个自定义按钮小部件,我想从那里访问根(主)window。

我知道 .master 属性,我可以用它来实现我想要的(见下面的代码)。但是因为按钮可能被放置在几十帧的内部很深的地方,所以我必须递归地获取.master直到我得到None。我想知道是否有更简洁的方法来获取程序的主要 window?

import tkinter as tk


class MyButton(tk.Button):
    def __init__(self, *args, **kwargs):
        super().__init__(bg="white", *args, **kwargs)

        root_window = self.master
        while root_window.master:
            root_window = root_window.master
        assert isinstance(root_window, tk.Tk)

        # in my particular case, the above code is equivalent to this:
        assert isinstance(self.master.master.master.master, tk.Tk)

        # but I'd like to be able to use something like that:
        # assert isinstance(self.root_window, tk.Tk)

root = tk.Tk()
frame1 = tk.Frame(root)
frame2 = tk.Frame(frame1)
frame3 = tk.Frame(frame2)
my_btn = MyButton(frame3)

for widget in (frame1, frame2, frame3, my_btn):
    widget.pack()

root.mainloop()

在任何小部件上调用 winfo_toplevel 将为您提供该小部件的根 window。