Python 如何将小部件彼此相邻放置?

Python 如何将小部件彼此相邻放置?,python,tkinter,Python,Tkinter,我正在构建一个简单的GUI程序来管理优先级。我无法将按钮小部件彼此相邻放置。对我来说,如果我想让三个按钮(添加、删除、编辑)相邻放置,我应该使用column=0表示添加,column=1表示删除,column=2表示编辑,这是合乎逻辑的。不管怎样,这就是我得到的: 以下是createWidgets函数: def createWidgets(self): listBox = Listbox(width = 30).grid(row=1, column = 0) Button(

我正在构建一个简单的GUI程序来管理优先级。我无法将按钮小部件彼此相邻放置。对我来说,如果我想让三个按钮(添加、删除、编辑)相邻放置,我应该使用column=0表示添加,column=1表示删除,column=2表示编辑,这是合乎逻辑的。不管怎样,这就是我得到的:

以下是createWidgets函数:

def createWidgets(self):

    listBox = Listbox(width = 30).grid(row=1, column = 0)

    Button(self.root,
                text = "Add",
                command = self.addItem).grid(row = 2, column = 1, sticky = W)

    Button(self.root,
           text="Remove",
           command = self.removeItem).grid(row = 2, column = 2, sticky = W)


    Button(self.root,
        text="Edit",
        command = self.editItem).grid(row = 2, column = 3, sticky = W)

    textBox = Text(height = 10, width = 30).grid(row = 3)
将该选项用于:

textBox = Text(height = 10, width = 30).grid(row = 3, column=0, columnspan=3) # specify the column also

当你这样做的时候

textBox = Text(height = 10, width = 30).grid(row = 3)
tkinter会自动设置
column=0
,因为
textBox
的宽度为30,所以第一列的宽度被拉伸为30。通过使用
columnspan
参数,可以放置
文本框
,使其占据所有列:

textBox = Text(height = 10, width = 30).grid(row = 3, column = 0, columnspan = 3)
由于
listBox
的宽度也为30,因此还应在此处使用
columnspan

listBox = Listbox(width = 30).grid(row=1, column = 0, columnspan = 3)

网格方法的综合指南是。

我的建议是将您的UI分解为多个区域,并独立管理每个区域。这比把所有东西塞进一个大网格要容易得多,尤其是当你有大小非常不同的小部件时

创建三个框架:一个用于顶部,一个用于按钮组,一个用于底部。然后,您可以使用
pack
将它们从上到下放置:

top_frame.pack(side="top", fill="both", expand=True)
button_frame.pack(side="top", fill="x")
bottom_frame.pack(side="bottom", fill="both", expand=True)
(使用
expand
取决于窗口变大时是否希望该框架展开)

一旦你做到了这一点,你就可以分别处理每个区域。例如,您可以使按钮成为按钮框的子按钮,并使用
.pack(side='left')
使其左对齐。其他小部件也可以使用
pack
,如果它们是每个其他框架中唯一的小部件,或者您可以使用
grid

您会发现,在开始编写代码之前只需几分钟就可以组织您的UI,这将大大提高创建和维护UI的难度

例子:
使用
columnspan
选项:`textBox=Text(高度=10,宽度=30)。grid(row=3,column=0,columnspan=3,sticky=W+E+N+S)`(并指定列)它稍微好一点,但它看起来还是不应该是这样的:我已经更新了我的答案,包括您还应该将
columnspan
参数添加到列表框中。比拉尔·贝盖拉杰在他的回答中已经提到了这一点。
top_frame.pack(side="top", fill="both", expand=True)
button_frame.pack(side="top", fill="x")
bottom_frame.pack(side="bottom", fill="both", expand=True)
def createWidgets(self):
    topFrame = tk.Frame(self)
    buttonFrame = tk.Frame(self)
    bottomFrame = tk.Frame(self)

    topFrame.pack(side="top", fill="both", expand=True)
    buttonFrame.pack(side="top", fill="x")
    bottomFrame.pack(side="bottom", fill="both", expand=True)

    listBox = tk.Listbox(topFrame, width=30)
    listBox.pack(side="top", fill="both", expand=True)

    tk.Button(buttonFrame, text="Add").pack(side="left")
    tk.Button(buttonFrame, text="Remove").pack(side="left")
    tk.Button(buttonFrame, text="Edit").pack(side="left")

    textBox = tk.Text(bottomFrame, height=10, width=30)
    textBox.pack(fill="both", expand=True)