您可以通过三个简单的步骤解决您的问题。首先,删除所有的padx
',因为它们会使按钮不对齐。其次,用于anchor = "w"
使按钮左对齐。第三,设置side
等于,"top"
使按钮垂直而不是水平放置。(但是,由于side
默认为“顶部”,您可以完全删除它)。以下是固定脚本:
from Tkinter import Tk, Button
root = Tk()
B = Button(root, text="BUTTON1")
C = Button(root, text="BUTTON2")
D = Button(root, text="BUTTON3")
B.pack(anchor = "w", pady = 0)
C.pack(anchor = "w", pady = 100)
D.pack(anchor = "w", pady = 120)
root.mainloop()
另一种选择是使用该grid
方法而不是pack
:
from Tkinter import Tk, Button, W
root = Tk()
B = Button(root, text="BUTTON1")
C = Button(root, text="BUTTON2")
D = Button(root, text="BUTTON3")
# 'row' sets the row number that the widget is placed on
# 'sticky' is the same as 'anchor'
B.grid(row=0, pady=0, sticky=W)
C.grid(row=1, pady=100, sticky=W)
D.grid(row=2, pady=120, sticky=W)
root.mainloop()
虽然我个人更喜欢grid
,pack
但这个决定实际上只是一个偏好问题。