pack()
1、pack函数布局的时候,默认先使用的放到上面,然后依次向下排列,默认方式它会给我们的组件一个自认为合适的位置和大小。
2、pack函数也可以接受几个参数,side参数,指定了它停靠在哪个方向,可以为LEFT,TOP,RIGHT,BOTTOM,分别代表左,上,右,下,
它的fill参数可以是X,Y,BOTH,NONE即在水平方向填充,竖直方向填充,水平和竖直方向填充和不填充。
3、它的expand参数可以是YES 和 NO,它的anchor参数可以是N,E,S,W(这里的NESW分别表示北东南西,这里分别表示上右下左)以及他们的组合或者是CENTER(表示中间)
4、它的ipadx表示的是内边距的x方向,它的ipady表示的是内边距的y的方向,padx表示的是外边距的x方向,pady表示的是外边距的y方向。
,必须强调pack()布局和控件的先后顺序是相关的,下面是完整例子,最终效果图片在下方,右边那幅图是AB交换顺序写的
接下来为了方便理解我们一个控件一个控件显示,看看是什么效果。
from tkinter import *
root =Tk()
root.geometry('400x300')
Button(root,text= "A",bg='red').pack(side = LEFT, expand = YES, fill = Y)
Button(root,text= "B").pack(side = TOP, expand = NO, fill = Y)
Button(root,text= "C").pack(side = RIGHT, expand = YES, fill = NONE,anchor = NE)
Button(root,text= "D").pack(side = LEFT, expand = NO, fill = Y)
Button(root,text= "E").pack(side = TOP, expand = NO, fill = BOTH)
Button(root,text= "F").pack(side = BOTTOM, expand = YES)
Button(root,text= "G").pack(anchor= SE)
root.mainloop()
交换ABbuttuon顺序
然后我们尝试一个一个输出首先是左边A按钮
Button(root,text= "A",bg='red').pack(side = LEFT, expand = YES, fill = BOTH/X/NONE)
然后我们输出第二个
Button(root,text= "A",bg='red').pack(side = LEFT, expand = YES, fill = Y)
Button(root,text= "B").pack(side = TOP, expand = YES/NO, fill = BOTH)
左边expand为YES 右边为NO
我们再输出第三个
Button(root,text= "A",bg='red').pack(side = LEFT, expand = YES, fill = Y)
Button(root,text= "B").pack(side = TOP, expand = NO, fill = X)
Button(root,text= "C").pack(side = RIGHT, expand = YES/NO, fill = NONE,anchor = NE)
左边是expand为yes 右边为NO
Button(root,text= "A",bg='red').pack(side = LEFT, expand = YES, fill = Y)
Button(root,text= "B").pack(side = TOP, expand = NO, fill = X)
Button(root,text= "C",bg='green').pack(side = RIGHT, expand = YES, fill = BOTH,anchor=NE)
Button(root,text= "D").pack(side = LEFT, expand = YES/NO, fill = Y)
左边expand为yes 右边为NO,可见expand就是扩展最大可达空间
Button(root,text= "A",bg='red').pack(side = LEFT, expand = YES, fill = Y)
Button(root,text= "B").pack(side = TOP, expand = NO, fill = X)
Button(root,text= "C",bg='green').pack(side = RIGHT, expand = YES, fill = BOTH,anchor=NE)
Button(root,text= "D").pack(side = LEFT, expand = NO/YES, fill = Y)
Button(root,text= "E").pack(side = TOP, expand = YES/NO, fill = BOTH)
Button(root,text= "A",bg='red').pack(side = LEFT, expand = YES, fill = Y)
Button(root,text= "B").pack(side = TOP, expand = NO, fill = X)
Button(root,text= "C",bg='green').pack(side = RIGHT, expand = YES, fill = BOTH,anchor=NE)
Button(root,text= "D").pack(side = LEFT, expand = YES, fill = Y)
Button(root,text= "E").pack(side = TOP, expand = YES, fill = BOTH)
Button(root,text= "F").pack(side = BOTTOM, expand =YES/NO)
左边expand为YES 右边为NO
总结:
由以上过程可知,pack会自动填充空间,而且下一个控件pack的地方永远是上一个空间pack完后剩余空间,关于expand属性,当其为真的时候,则会将其能扩展的最大空间,