我如何堆叠按钮而不是在 Tkinter 中将它们排队?
How can I stack buttons rather than queue them in Tkinter?
目前我显示了 3 个基本按钮:
from tkinter import *
root = Tk()
topFrame = Frame(root)
topFrame.pack(side=TOP)
leftFrame = Frame(root)
leftFrame.pack(side=LEFT)
botFrame = Frame(root)
botFrame.pack(side=BOTTOM)
button1 = Button(leftFrame, text="Button 1", fg="Black")
button2 = Button(leftFrame, text="Button 2", fg="Black")
button3 = Button(leftFrame, text="Button 3", fg="Black")
button1.pack(side=LEFT)
button2.pack(side=LEFT)
button3.pack(side=LEFT)
root.mainloop()
此时的 3 个按钮会粘在 window 的左框架上,但是它们会并排排列,而不是一个叠一个,我该如何解决这个问题?
探索 grid
函数。将您的 pack
语句更改为
button1.grid(row=0,column=0)
button2.grid(row=1,column=0)
button3.grid(row=2,column=0)
您明确告诉他们要与 side=LEFT
肩并肩。您希望 side=TOP
将它们放置在框架中空 space 的顶部。
button1.pack(side=TOP)
button2.pack(side=TOP)
button3.pack(side=TOP)
当您使用 pack 时,值 TOP、LEFT、RIGHT 和 BOTTOM 告诉小部件它们应该占据 remaining space 的哪一侧。第一次使用 LEFT 时,它将为小部件保留整个框架的左侧。下次您使用 LEFT 时,它指的是小部件 中剩余的 space 不包括 左边缘,因为其中已经有一个小部件。最终效果是 LEFT 使小部件从左到右排列,RIGHT 使它们从右到左排列,依此类推。
目前我显示了 3 个基本按钮:
from tkinter import *
root = Tk()
topFrame = Frame(root)
topFrame.pack(side=TOP)
leftFrame = Frame(root)
leftFrame.pack(side=LEFT)
botFrame = Frame(root)
botFrame.pack(side=BOTTOM)
button1 = Button(leftFrame, text="Button 1", fg="Black")
button2 = Button(leftFrame, text="Button 2", fg="Black")
button3 = Button(leftFrame, text="Button 3", fg="Black")
button1.pack(side=LEFT)
button2.pack(side=LEFT)
button3.pack(side=LEFT)
root.mainloop()
此时的 3 个按钮会粘在 window 的左框架上,但是它们会并排排列,而不是一个叠一个,我该如何解决这个问题?
探索 grid
函数。将您的 pack
语句更改为
button1.grid(row=0,column=0)
button2.grid(row=1,column=0)
button3.grid(row=2,column=0)
您明确告诉他们要与 side=LEFT
肩并肩。您希望 side=TOP
将它们放置在框架中空 space 的顶部。
button1.pack(side=TOP)
button2.pack(side=TOP)
button3.pack(side=TOP)
当您使用 pack 时,值 TOP、LEFT、RIGHT 和 BOTTOM 告诉小部件它们应该占据 remaining space 的哪一侧。第一次使用 LEFT 时,它将为小部件保留整个框架的左侧。下次您使用 LEFT 时,它指的是小部件 中剩余的 space 不包括 左边缘,因为其中已经有一个小部件。最终效果是 LEFT 使小部件从左到右排列,RIGHT 使它们从右到左排列,依此类推。