Grid(网格)布局管理器,是Tkinter里面最灵活的几何管理布局器。注意:不要试图在一个主窗口中混合使用pack和grid。
1.简单的布局
from tkinter import *
root = Tk()
label1 = Label(root, text="用户名:")
label2 = Label(root, text="密码:")
entry1 = Entry(root)
entry2 = Entry(root)
label1.grid(row=0, padx='10', pady='10')
label2.grid(row=1)
entry1.grid(row=0, column=1, padx='10', pady='10')
entry2.grid(row=1, column=1, padx='10', pady='10')
mainloop()
运行结果
说明:
(1) label1没写column属性,默认从0开始
(2) padx 控件与外边框的水平距离;ipadx 控件内文字与控件边框的距离;pady/ipady同理
2. 对齐方式sticky、合并行rowspan、合并列columnspan
from tkinter import * root = Tk() label1 = Label(root, text="用户名:") label2 = Label(root, text="密码:") entry1 = Entry(root) entry2 = Entry(root) btn1 = Button(root, text="登 录", width='15') label1.grid(row=0, sticky=E, padx='5') label2.grid(row=1, sticky=E, padx='5') entry1.grid(row=0, column=1, padx='5', pady='10') entry2.grid(row=1, column=1, padx='5', pady='10') btn1.grid(row=2, column=0, columnspan=2, pady='10') mainloop()
运行效果:
说明
(1) sticky可选的值:N/S/E/W,分别代表上/下/左/右。sticky=E表示靠右显示。
(2) columnspan合并列
3.frame结合grid布局
对稍复杂的布局,网格实现起来费劲的话考虑外层加frame
from tkinter import * root = Tk() frm = Frame(root) frm.grid(padx='10', pady='10') frm_left = Frame(frm) frm_left.grid(row=0, column=0, padx='20', pady='10') frm_right = Frame(frm) frm_right.grid(row=0, column=1, padx='20', pady='10') btn_left1 = Button(frm_left, text='按 钮 1') btn_left1.grid(row=0, pady='20', ipadx='2', ipady='2') btn_left2 = Button(frm_left, text='按 钮 2') btn_left2.grid(row=1, pady='20', ipadx='2', ipady='2') btn_left3 = Button(frm_left, text='按 钮 3') btn_left3.grid(row=2, pady='20', ipadx='2', ipady='2') btn_left4 = Button(frm_left, text='按 钮 4') btn_left4.grid(row=3, pady='20', ipadx='2', ipady='2') btn_right1 = Button(frm_right, text='按 钮 5') btn_right1.grid(row=0, column=0, ipadx='2', ipady='2') btn_right2 = Button(frm_right, text='按 钮 6') btn_right2.grid(row=0, column=1, ipadx='2', ipady='2') txt_right = Text(frm_right, width='45', height='15') txt_right.grid(row=1, column=0, columnspan=2, pady='20') root.mainloop()