Tkinter pack()布局


Tkinter pack()布局

pack 管理器是根據我們在代碼中添加組件的順序依次排列所有組件,非常簡單方便。

通常來說,pack 適用於少量組件或簡單布局的情況。它不像 place 和 grid 布局管理器需要計算位置(坐標或者行列),pack 只有上下左右的關系,一個個按添加順序放上去即可。

 

1. pack 縱向依次排列

在默認情況下,使用 pack 方法就是將各個組件按照添加順序縱向依次排列。

import tkinter as tk 

root = tk.Tk()

tk.Label(root, text="Red", bg="red", fg="white").pack()
tk.Label(root, text="Yellow", bg="yellow", fg="black").pack()
tk.Label(root, text="Green", bg="green", fg="white").pack()
tk.Label(root, text="Blue", bg="blue", fg="white").pack()

root.mainloop()

 

 

 

2. pack 橫向依次排列

如果我們希望所有組件按照順序橫向依次排列,我們可以添加參數 side='left',從而就實現了從左往右的橫向排列效果。

import tkinter as tk 

root = tk.Tk()

tk.Label(root, text="Red", bg="red", fg="white").pack(side='left')
tk.Label(root, text="Yellow", bg="yellow", fg="black").pack(side='left')
tk.Label(root, text="Green", bg="green", fg="white").pack(side='left')
tk.Label(root, text="Blue", bg="blue", fg="white").pack(side='left')

root.mainloop()

 

 

3. pack 的復雜布局效果

我們再來試一試相對比較多的組件下復雜的 pack 布局。

為了實現整個布局的整齊美觀,我們通常會設置fill、expand參數。

fill 表示填充分配空間
    x:水平方向填充
    y:豎直方向填充
    both:水平和豎直方向填充
    none:不填充(默認值)

expand 表示是否填充父組件的額外空間
    True 擴展整個空白區
    False 不擴展(默認值)

 

expand置True 使能fill屬性
expand置False 關閉fill屬性 fill=X 當GUI窗體大小發生變化時,widget在X方向跟隨GUI窗體變化 fill=Y 當GUI窗體大小發生變化時,widget在Y方向跟隨GUI窗體變化 fill=BOTH 當GUI窗體大小發生變化時,widget在X、Y兩方向跟隨GUI窗體變化

 

import tkinter as tk 

root = tk.Tk()

letter = ['A','B','C','D','E']

for i in letter:
    tk.Label(root, text=i, relief='groove').pack(fill='both', expand=True)
for i in letter:
    tk.Label(root, text=i, relief='groove').pack(side='left', fill='both', expand=True)
for i in letter:
    tk.Label(root, text=i, relief='groove').pack(side='bottom', fill='both', expand=True)
for i in letter:
    tk.Label(root, text=i, relief='groove').pack(side='right',fill='both', expand=True)
 
root.mainloop()

 

 

 

三、參數方法

1. 參數匯總

布局管理器 pack 涉及的相關參數以及用法。

 

 

 

 


原文鏈接:https://blog.csdn.net/nilvya/article/details/106148018

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM