Pack 基本版面布局
通常在使用 tkinter 时,第一步都会使用 pack() 方法来放置元件,这篇教学会介绍如何使用 pack() 方法,并进行基本的元件排版布局。
快速导览:
因为 Google Colab 不支援 tkinter,所以请使用本机环境 ( 参考:使用 Python 虚拟环境 ) 或使用 Anaconda Jupyter 进行实作 ( 参考:使用 Anaconda )。
使用 pack()
使用 tkinter 相关方法建立元件后,必须搭配 pack() 才能将该元件放到另外一个指定的元件里,以下方的例子而言,有两个 Label 都指向 root ( 主视窗元件 ),使用 pack() 后就会按照执行的顺序,由上而下放置。
import tkinter as tk
root = tk.Tk()
root.title('oxxo.studio')
root.geometry('200x200')
a = tk.Label(root, text='AAA', background='#f90')
b = tk.Label(root, text='BBB', background='#09c')
a.pack()
b.pack()
root.mainloop()
fill 参数
pack() 的 fill 参数默认使用元件宽度,设定 fill='x' 表示和放置的父元件同宽 ( 必须搭配 side 参数设定默认值、top、bottom 或 expand 参数 ),设定 fill='y' 表示和放置的父元件同高 ( 必须搭配 side 参数设定 left、right 或 expand 参数 ),设定 fill='both' 表示同时撑满水平和垂直方向。
import tkinter as tk
root = tk.Tk()
root.title('oxxo.studio')
root.geometry('200x200')
a = tk.Label(root, text='AAA', background='#f90')
b = tk.Label(root, text='BBB', background='#09c')
a.pack(fill='x')
b.pack(fill='y', side='left')
root.mainloop()
expand 参数
如果要让两个元件一个一半的撑满某个方向,可以使用 fill 参数配 expand 参数,expand 默认为 0 表示使用元件本身长宽,若设定为 1 则会展开。
import tkinter as tk
root = tk.Tk()
root.title('oxxo.studio')
root.geometry('200x200')
a = tk.Label(root, text='AAA', background='#f90')
b = tk.Label(root, text='BBB', background='#09c')
a.pack(fill='y', expand=1)
b.pack(fill='both', expand=1)
root.mainloop()
padx、pady、ipadx、ipady 参数
pack() 的 padx 参数表示左右外边距,pady 表示上下外边距,ipadx 表示左右内边距,ipady 表示上下内边距,四个参数默认值均为 0,下方的程序码执行后,会表现出不同参数设定的结果。
import tkinter as tk
root = tk.Tk()
root.title('oxxo.studio')
root.geometry('200x200')
a = tk.Label(root, text='AAA', background='#f90')
b = tk.Label(root, text='BBB', background='#09c')
c = tk.Label(root, text='CCC', background='#fc0')
d = tk.Label(root, text='DDD', background='#f9c')
e = tk.Label(root, text='EEE', background='#aaa')
a.pack(fill='x', padx=20)
b.pack(ipadx=20)
c.pack(fill='x', ipady=20)
d.pack(ipady=20)
e.pack()
root.mainloop()
side 参数
pack() 的 side 参数会设定该元件放置在 left 左边、right 右边、top 上面、bottom 下面,执行的顺序决定放置的顺序。
import tkinter as tk
root = tk.Tk()
root.title('oxxo.studio')
root.geometry('200x200')
a = tk.Label(root, text='AAA', background='#f90')
b = tk.Label(root, text='BBB', background='#09c')
c = tk.Label(root, text='CCC', background='#fc0')
d = tk.Label(root, text='DDD', background='#f9c')
e = tk.Label(root, text='EEE', background='#aaa')
a.pack(side='left')
b.pack(side='left')
c.pack(side='top')
d.pack(side='bottom')
e.pack(side='right')
root.mainloop()
微信扫码关注
抖音扫码关注