我是Tkinter
的新手,我正在制作一个非常简单的GUI。来自 JavaFX 背景的我发现它有点令人困惑,因为我无法将按钮位置基于坐标。
这是我的实际代码:
class MoveRobot(Frame):
grid_counter = 0
def __init__(self):
Frame.__init__(self)
self.master.title("Control Robot")
self.master.geometry("400x400")
self.master.rowconfigure(0, weight=1)
self.master.columnconfigure(0, weight=1)
self.grid(sticky=W + E + N + S)
self.list_box = Listbox(self)
self.list_box.grid(rowspan=4, sticky=W + E + N + S)
self.button1 = Button(self, text="UP", command=self.button_up)
self.button1.grid(row=0, column=1, columnspan=2, sticky=W + E + N + S)
self.button2 = Button(self, text="DOWN", command=self.button_down)
self.button2.grid(row=1, column=1, columnspan=2, sticky=W + E + N + S)
self.button3 = Button(self, text="LEFT", command=self.button_left)
self.button3.grid(row=2, column=1, columnspan=2, sticky=W + E + N + S)
self.button4 = Button(self, text="RIGHT", command=self.button_right)
self.button4.grid(row=3, column=1, columnspan=2, sticky=W + E + N + S)
self.button_cancel = Button(self, text="Remove Last", command=self.button_remove_last)
self.button_cancel.grid(row=4, columnspan=2, sticky=W + E + N + S)
self.button_cancel = Button(self, text="Clear", command=self.button_clear)
self.button_cancel.grid(row=5, columnspan=2, sticky=W + E + N + S)
self.button_compile = Button(self, text="Compile", command=self.button_compile)
self.button_compile.grid(row=6, columnspan=2, sticky=W + E + N + S)
self.rowconfigure(1, weight=1)
self.columnconfigure(1, weight=1)
#controller code is removed because unnecessary
def main():
MoveRobot().mainloop()
if __name__ == "__main__":
main()
下面是我创建的 GUI。
但是,我无法将“向上”、“向下”、“向左”和“向右”按钮粘在一起。我尝试查看论坛和网站,但找不到解决方案。它应该非常简单,因为这只是一个布局问题。
我想要的输出应该是这样的..
有人可以帮忙吗?我希望这个问题对其他人也有好处,因为我不知道如何使用 Tkinter,也无法在网络上找到解决方案。
提前谢谢您。
最佳答案
解决布局问题的技巧是将 UI 分成几个部分,并一次专注于一个部分。在您的情况下,我看到三个部分:左侧的列表框、右侧的一组按钮和底部的一组按钮。
由于您具体询问右侧的按钮,因此我将在本答案中讨论该组。
在我看来,最简单的解决方案是为按钮创建一个框架,然后将按钮打包在框架的顶部:
button_frame = Frame(self)
self.button1 = Button(button_frame, ...)
self.button2 = Button(button_frame, ...)
self.button3 = Button(button_frame, ...)
self.button4 = Button(button_frame, ...)
self.button1.pack(side="top", fill="x")
self.button2.pack(side="top", fill="x")
self.button3.pack(side="top", fill="x")
self.button4.pack(side="top", fill="x")
这样,无论您将该框架放在哪里,按钮都将始终位于顶部。在您的情况下,您可以将列表框和框架放在同一行:
self.list_box.grid(row=0, column=0, sticky="nsew")
button_frame.grid(row=0, column=1, sticky="nsew")
关于python - 布局 - Tkinter - 将按钮分组在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43526215/