Place 位置版面布局
除了 place() 和 grid(),tkinter 也有提供 place() 的布局方法,让用户可以定义“绝对位置”和“相对位置”的座标进行元件定位,这篇教学会介绍如何使用 place() 方法,并使用位置的方式进行元件的排版布局。
快速导览:
因为 Google Colab 不支援 tkinter,所以请使用本机环境 ( 参考:使用 Python 虚拟环境 ) 或使用 Anaconda Jupyter 进行实作 ( 参考:使用 Anaconda )。
使用 place()
使用 tkinter 相关方法建立元件后,除了使用 pack() 方法 ( 参考 Pack 基本版面布局 ) 和 grid() 方法 ( 参考 Grid 格状版面布局 ) 进行放置外,也可以使用 place() 方法将元件摆放在指定的位置,不受基本放置或格状版面影响,以下方的例子而言,有四个 Label 都指向 root ( 主视窗元件 ),使用 place() 将其放在指定的座标上。
注意,使用 place() 方法只能放在主视窗 root 里,不能放在其他元件 ( 如 Frame 中 )。
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='#0c9')
a.place(x=0, y=0) # 放在 (0,0)
b.place(x=50, y=50) # 放在 (50,50)
c.place(x=100, y=100) # 放在 (100,100)
d.place(x=150, y=150) # 放在 (150,150)
root.mainloop()
x、y 参数
place() 的 x 和 y 参数表示放置的元件在主视窗的绝对位置,视窗左上角为 (0,0),往右为正,往下为正,下方的程序码执行后,会有四个 Label 放在指定的位置上。
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='#0c9')
a.place(x=0, y=0) # 放在 (0,0)
b.place(x=50, y=50) # 放在 (50,50)
c.place(x=100, y=100) # 放在 (100,100)
d.place(x=150, y=150) # 放在 (150,150)
root.mainloop()
relx、rely 参数
place() 的 relx 和 rely 参数表示“比例”,也就是元件左上角座标在视窗中,按照比例算出来的座标,数值范围 0~1,例如视窗宽度如果是 100,relx 设定 0.5,x 座标就会在 100x0.5=50 的位置。
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='#0c9')
a.place(relx=0.1, rely=0.1)
b.place(relx=0.3, rely=0.3)
c.place(relx=0.5, rely=0.5)
d.place(relx=0.7, rely=0.7)
root.mainloop()
微信扫码关注
抖音扫码关注