使用 self.pack 和 self.grid 可以在没有 类 的情况下工作,但会失败

Using self.pack and self.grid works without classes, but fails with them

所以我尝试使用Tkinter Button Alignment in Grid来制作工具栏,但不同的是我使用类。因此,当他们使用 frame.pack 和 button.grid 时,我得到同时使用 pack 和 grid 的错误。这是我的代码:

class Application(Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.master.title('Hi!')
        self.master.configure(bg='dark grey')
        self.pack(fill=X, side=TOP)
        self.create_toolbar()

    def create_toolbar(self):
        Home = Button(text='Home', bd=1)
        About = Button(text='About', bd=1)

        self.columnconfigure(0, weight=1)
        self.columnconfigure(1, weight=1)

        Home.grid(row=0, column=0, sticky=W+E)
        About.grid(row=0, column=1, sticky=W+E)

在我看来,这里的问题是 Widget 没有 master 集,因此它们默认为 class' master,您已经在其中使用 pack 进行几何管理。

这里的解决方案是在声明小部件时设置 master=self,然后当您将小部件放置在 tk.Frame 对象中时,您可以使用网格。