如何防止 Tkinter 从属小部件指示自己的位置?

问题描述

所以我有两个框架,一个居中的文本框架和一个带有按钮的工具栏。我希望工具栏位于顶部,所以我尝试了 self.toolbar.pack(side='top',pady=60),但似乎还不够。

发生的情况是,作为工具栏框架从属的按钮似乎在规定自己的位置:如果我 pack 一个左,它会在整个应用程序的左侧。相反,我希望能够放置一次我的工具栏框架,然后pack我的按钮并排放置,因此使用诸如当前更改其全局位置的 side 属性之类的东西。

我怎样才能做到这一点?我的 OOP 方法写得不好?

整个区块:

import tkinter as tk


class ToolbarButton(tk.Button):

    def __init__(self,master,text,pixelref,*args,**kw):
        super(ToolbarButton,self).__init__()
        self.master = master
        super(ToolbarButton,self).configure(text=text,image=pixelref,height=20,width=20,compound='center')


class MainApplication(tk.Frame):
    def __init__(self,parent,**kwargs):
        tk.Frame.__init__(self,**kwargs)
        self.parent = parent

        # Textframe
        self.text_frame = tk.Frame(root,width=600,height=790)
        self.text_frame.pack_propagate(False)
        self.text_widg = tk.Text(self.text_frame,width=1,height=1)
        self.text_widg.pack(expand=True,fill='both')

        # Toolbar
        self.toolbar = tk.Frame(root)
        self.pixel = tk.PhotoImage(width=1,height=1)

        self.bold_button = ToolbarButton(self.toolbar,'B',self.pixel)
        self.bold_button.pack(side='left',padx=4)
        self.italic_button = ToolbarButton(self.toolbar,'I',self.pixel)
        self.italic_button.pack(side='left',padx=4)
        self.underline_button = ToolbarButton(self.toolbar,'U',self.pixel)
        self.underline_button.pack(side='left',padx=4)

        # Packing
        self.toolbar.pack(side='top',pady=60)
        self.text_frame.pack(expand=True)


if __name__ == "__main__":
    root = tk.Tk()
    MainApplication(root).pack(side="top",fill="both",expand=True)
    root.mainloop()

解决方法

有人向我解释了这个问题:ToolbarButton 类没有正确实例化。 一种纠正此问题的方法 - 并改进语法:

class ToolbarButton(tk.Button):
    def __init__(self,master,text,pixelref,*args,**kw):
        super().__init__(master)
        self.configure(text=text,image=pixelref,height=20,width=20,compound='center')