禁止同时使用两种布局方式,只能出现其中的一种
pack布局
widget.pack(**kwargs)
side='top|buttom|left|right':组件相对父件在哪一边,默认'top'ipadx,ipady:组件内部在x和y方向上填充空间的大小(内间距),理解为padding
padx,pady:组件外部在x和y方向上填充空间的大小(外间距),可以理解为marginfill='x|y|both|none':‘x方向填充|y方向填充|x、y方向都填充|x、y方向都不填充’。可以理解为无论按钮多大,都让它占满一整行或一整列。注意,要使在y方向填充满必须设置side参数在左边或右边。expand='yes|no':设置side是否失效。'yes'时,side失效,组件显示在父配件中心位置;若当fill='both'时,则填充父组件的剩余空间。默认为'no'或0。- 注意:仅仅使用pack()无法实现表格方式,必须借助后面的Frame组件才可以实现
import tkinter as tk
root = tk.Tk()
root.minsize(500, 300)
# 使用wm_title也可以设置标题
root.wm_title("3种摆放方式")
button_0 = tk.Button(root, text='Hello 迪丽热巴!')
button_0.pack(side='left') # 组件的位置
button_1 = tk.Button(root, text='Hello 古力娜扎!')
button_1.pack(ipadx=60) # 组件的内部间距
button_2 = tk.Button(root, text='Hello 马儿扎哈!')
button_2.pack(pady=20) # 组件之间的外部间距
button_3 = tk.Button(root, text='Hello 沙扬娜拉!')
button_3.pack(fill='x', side='bottom') # 占据x或y方向的最大位置
button_3 = tk.Button(root, text='Hello meijun!')
button_3.pack(fill='both', expand='yes') # 允许按钮横向和纵向填充
root.mainloop()

grid布局
widget.grid(**kwargs):
row:行数,从0开始,默认为0column:列数,从0开始,默认为0rowspan:设置跨行数,默认为0columnspan:设置跨列数,默认为0ipadx, ipady:设置组件的内部间距,理解为paddingpadx, pady:设置组件的外部间距,理解为marginsticky='center':组件紧靠所在单元格的某一边角。可设置'n', 's', 'e', 'w', 'nw', 'sw', 'ne', 'se', 'center'(默认)- 注意:网格没有固定大小,网格大小取决于最大的组件大小
import tkinter as tk
root = tk.Tk()
root.minsize(500, 300)
root.wm_title("3种摆放方式")
button_0 = tk.Button(root, text='Hello 迪丽热巴')
button_0.grid()
button_1 = tk.Button(root, text='Hello 古力娜扎')
button_1.grid(row=0, column=1)
button_2 = tk.Button(root, text='Hello 马儿扎哈')
button_2.grid(row=1, column=0)
button_3 = tk.Button(root, text='Hello 沙扬娜拉')
button_3.grid(row=1, column=1)
button_4 = tk.Button(root, text='Hello 阿兹尔')
button_4.grid(row=2, column=0, columnspan=2, ipadx=50)
button_5 = tk.Button(root, text='Hello meijun')
button_5.grid(row=0, column=2, rowspan=2, ipady=20)
root.mainloop()

place布局
绝对定位
widget.place(**kwargs):单位为像素
x, y:笛卡尔坐标width, height: 宽度、高度anthor:锚点,相对于摆放组件的坐标和位置参阅,取值为N,S,E,W...,默认nw
相对定位
widget.place(**kwargs):单位为百分比
relx, rely:相对于root窗口的百分比坐标,取值[0,1]relwidth,relheight:组件相对于root窗口的宽度和高度,取值范围为[0,1]
import tkinter as tk
root = tk.Tk()
root.minsize(500, 300)
root.wm_title("3种摆放方式")
# 绝对定位
button_0 = tk.Button(root, text='Hello! 迪丽热巴')
button_0.place(x=100, y=100, anchor='sw')
button_1 = tk.Button(root, text='Hi! 古力娜扎')
button_1.place(x=200, y=100, width=100, height=50)
# 相对定位
button_2 = tk.Button(root, text='Hello! 马儿扎哈', bg='pink')
button_2.place(relx=0.2, rely=0.5)
button_3 = tk.Button(root, text='Hi! 沙扬娜拉', bg='pink')
button_3.place(relx=0.7, rely=0.7, relwidth=0.3, relheight=0.3)
root.mainloop()

本文介绍了Tkinter库中三种布局方式:pack、grid和place,分别讲解了它们的参数、功能和使用示例,如组件位置、间距设置以及绝对/相对定位。
1325

被折叠的 条评论
为什么被折叠?



