如何使用grid()python

时间:2013-07-05 16:56:12

标签: python grid tkinter

如何使用grid()将小部件放在窗口的底部?例如,这段代码会将这些标签放在彼此的正下方,但是如果我想将label_4移动到窗口的底部,或者更接近底部,那该怎么办呢?

label_1 = Label(text = 'Name 1').grid(row = 0, sticky = W)
label_2 = Label(text = 'Name 2').grid(row = 1, sticky = W)
label_3 = Label(text = 'Name 3').grid(row = 2, sticky = W)
label_4 = Label(text = 'Name 4').grid(row = 3, sticky = W)

1 个答案:

答案 0 :(得分:2)

如果你想为此使用网格系统,你必须在网格系统(一个空的)中创建一个“spacer”单元格,它可以动态地从窗口中获取空格,并将最后一个标签推送到底部。

from Tkinter import *  # or tkinter if you use Python3

root = Tk()

label_1 = Label(master=root, text='Name 1')
label_2 = Label(master=root, text='Name 2')
label_3 = Label(master=root, text='Name 3')
label_4 = Label(master=root, text='Name 4')

label_1.grid(row=0)
label_2.grid(row=1)
label_3.grid(row=2)  # this is the 2nd
label_4.grid(row=4)  # this is the 4th

root.rowconfigure(index=3, weight=1)  # add weight to the 3rd!
root.mainloop()

但是对于这个简单的场景,我认为你应该使用pack代替grid

from Tkinter import *  # or tkinter if you use Python3

root = Tk()

label_1 = Label(master=root, text='Name 1')
label_2 = Label(master=root, text='Name 2')
label_3 = Label(master=root, text='Name 3')
label_4 = Label(master=root, text='Name 4')

label_1.pack()
label_2.pack()
label_3.pack()
label_4.pack(side=BOTTOM)

root.mainloop()