如何连续排列按钮?

时间:2013-03-21 20:10:18

标签: python user-interface tkinter

我已经定义了单独的函数,并且具有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 个答案:

答案 0 :(得分: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)

请注意,您总是使用几乎相同的代码,因此如果您使用for循环并预先声明小部件的选项,它可能看起来更干净。

答案 1 :(得分:1)

pack()更改为pack(side='left')

相关问题