我正在构建一个简单的GUI程序来管理优先级。我无法将按钮小部件放在一起。对我来说,如果我想要三个按钮(添加,删除,编辑)放在一起,我应该使用column = 0表示Add,列= 1表示删除,列= 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)
答案 0 :(得分:2)
使用columnspan
选项:
textBox = Text(height = 10, width = 30).grid(row = 3, column=0, columnspan=3) # specify the column also
和
listBox = Listbox(width = 30).grid(row=1, column = 0, columnspan=3)
答案 1 :(得分:2)
当你这样做时
textBox = Text(height = 10, width = 30).grid(row = 3)
tkinter自动设置column = 0
,因为textBox
的宽度为30,所以第一列的宽度为30。可以放置textBox
以使其占据所有列使用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)
网格方法的综合指南是Content Settings-Chrome。
答案 2 :(得分:2)
我的建议是将用户界面分解为多个区域,并独立管理每个区域。它比将所有东西塞入一个大网格要容易得多,特别是当你的小部件尺寸不同时。
创建三个框架:一个用于顶部,一个用于按钮组,一个用于底部。然后,您可以使用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
。
您会发现在开始编写代码之前只需几分钟的时间来组织您的用户界面会对创建和维护的难易程度产生重大影响。
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)