推荐阅读:
pack()
pack()布局方式较为简单,向程序中添加组件时,这些组件会依次向后排列,排列方向可以是水平或垂直的,主适用于少量组件的顺序排列
案例:pack向窗口中添加三个标签
import tkinter
root=tkinter.Tk()
root.title('pack布局')
for i in rnage(3):
label=tkinter.Label(root,text=f'第{i+1}个标签')
label.pack()
root.mainloop()
运行结果
pack布局参数
我们使用help方法查看pack方法支持的选项
从上面的显示信息我们可以看出pack方法支持的参数
参数 | 描述 | 值 |
---|---|---|
anchor | 设置组件被放置在容器何处 | N,E,S,W,NW,NE,SW,SE,CENTER |
expand | 当父容器增大时是否拉伸组件 | True/False |
fill | 设置组件沿着水平或竖直方向填充 | NONE,X,Y,BOTH |
ipadx | 指定组件在x方向上的内部留白 | |
ipadx | 指定组件在y方向上的内部留白 | |
padx | 指定组件在x方向上与其它组件的间距 | |
pady | 指定组件在y方向上与其它组件的间距 | |
side | 设置组件的添加位置, | TOP,BOTTOM,LEFT,RIGHT |
案例:pack布局简单使用
from tkinter import *
class App:
def __init__(self,master):
self.master=master
self.fun()
def fun(self):
# 创建第一个容器
fm1=Frame(self.master)
fm1.pack(side=LEFT,fill=BOTH,expand=True) # 设置容器1放在父窗体左边,BOTH表示按钮沿两个方向填充,父容器增大时拉伸
Button(fm1,text='按钮1').pack(side=TOP,fill=X,expand=True) # 按钮从顶部开始排列,且按钮只能在水平方向上填充
Button(fm1,text='按钮2').pack(side=TOP,fill=X,expand=True)
Button(fm1,text='按钮3').pack(side=TOP,fill=X,expand=True)
# 创建第二个容器
fm2=Frame(self.master)
fm2.pack(side=LEFT,padx=10,expand=True)
Button(fm2,text='按钮x').pack(side=RIGHT,fill=Y,expand=True) # 三个按钮从右向左依次排列
Button(fm2,text='按钮y').pack(side=RIGHT,fill=Y,expand=True)
Button(fm2,text='按钮z').pack(side=RIGHT,fill=Y,expand=True)
fm3=Frame(self.master)
fm3.pack(side=RIGHT,padx=10,fill=BOTH,expand=True)
tkinter.Button(fm3,text='按钮a').pack(side=BOTTOM,fill=X,expand=True)
tkinter.Button(fm3,text='按钮b').pack(side=BOTTOM,fill=X,expand=True)
tkinter.Button(fm3,text='按钮c').pack(side=BOTTOM,fill=X,expand=True)
root=Tk()
root.title('pack布局')
display=App(root)
root.mainloop()
运行结果