如何将按钮排列在一行?
我定义了几个不同的函数,还有一个 main()
函数。在这个 main()
函数里,我放了几个按钮,当点击这些按钮时,它们会调用其他的函数。
def main():
global root
global tkinter
global canvas
root = Tk()
root.title("Shapes Quiz - Flow Computing")
Button(root, text ="1", bg="Grey", width=10, command=pentagon).pack()
Button(root, text ="2", bg="Grey", width=10, command=circle).pack()
Button(root, text ="3", bg="Grey", width=10, command=diamond).pack()
Button(root, text ="4", bg="Grey", width=10, command=hexagon).pack()
Button(root, text ="5", bg="Grey", width=10, command=triangle).pack()
Button(root, text ="6", bg="Grey", width=10, command=square).pack()
Button(root, text ="7", bg="Grey", width=10, command=rectangle).pack()
Button(root, text ="8", bg="Grey", width=10, command=heptagon).pack()
Button(root, text ="9", bg="Grey", width=10, command=octagon).pack()
Button(root, text ="10", bg="Grey", width=10, command=oval).pack()
Button(root, text ="Help", bg="Grey", width=10, command=help).pack()
Button(root, text ="Clear", bg="Red", width=10, command=clearshapes).pack()
Button(root, text ="QUIT", bg="Red", width=10, command=quit).pack()
我觉得应该有更简单的方法来整理这些按钮。我听说过可以用框架、网格,甚至坐标来布局,但我还是不太清楚具体怎么做。
我想把按钮排成 横向,而不是现在这样 纵向 显示。
2 个回答
2
当然,有一种更简单的方法可以做到这一点,那就是使用网格几何管理器(评论里已经有链接了):
# ...
root.title("Shapes Quiz - Flow Computing")
BUTTONS = [{"text":"1", "bg":"Grey", "width":10, "command":pentagon},
{"text":"2", "bg":"Grey", "width":10, "command":circle},
# Rest of the buttons
{"text":"QUIT", "bg":"Red", "width":10, "command":quit}]
for i, options in enumerate(BUTTONS):
Button(root, **options).grid(row=0, column=i)
请注意,你几乎总是使用相似的代码,所以如果你提前声明好小部件的选项,使用一个循环会让代码看起来更整洁。
2
把 pack()
改成 pack(side='left')
。