python中tkinter三大布局方式之一的grid,简单示例:
grid也叫网格布局,用tkinter写gui的时候用的比较多,下面用示例来解析部分属性的使用:
row是行号,column是列号,都是从0开始订数,sticky(取值包含 N,E,S,W,NW,NE,SW,SE)是对齐方式,
l1 = tk.Label(root, text='标签1', bg='red', width='20').grid(row=0,column=0,sticky=tk.W)
l2 = tk.Label(root, text='标签2', bg='orange', width='20').grid(row=0,column=1,sticky=tk.W)
l3 = tk.Label(root, text='标签3', bg='yellow', width='20').grid(row=0,column=2,sticky=tk.W)
l4 = tk.Label(root, text='标签4', bg='green', width='20').grid(row=1,column=0,sticky=tk.W)
l5 = tk.Label(root, text='标签5', bg='blue', width='20').grid(row=1,column=1,sticky=tk.W)
l6 = tk.Label(root, text='标签6', bg='black', width='20').grid(row=1,column=2,sticky=tk.W)
columnspan合并列,rowspan合并行的使用:
l7 = tk.Label(root, text='标签7', bg='pink',width='62').grid(row=2,column=0,columnspan=3)
l9 = tk.Label(root, text='标签9', bg='pink',width='62').grid(row=3,column=0,columnspan=3)
l8 = tk.Label(root, text='标签8', bg='purple',width='62').grid(row=2,column=0,rowspan=2,columnspan=3)
完整代码:
import tkinter as tk
root = tk.Tk()
root.title("grid简单示例")
##grid布局简单示例
##row是行号,column是列号,都是从0开始订数,sticky是对齐方式,
l1 = tk.Label(root, text='标签1', bg='red', width='20').grid(row=0,column=0,sticky=tk.W)
l2 = tk.Label(root, text='标签2', bg='orange', width='20').grid(row=0,column=1,sticky=tk.W)
l3 = tk.Label(root, text='标签3', bg='yellow', width='20').grid(row=0,column=2,sticky=tk.W)
l4 = tk.Label(root, text='标签4', bg='green', width='20').grid(row=1,column=0,sticky=tk.W)
l5 = tk.Label(root, text='标签5', bg='blue', width='20').grid(row=1,column=1,sticky=tk.W)
l6 = tk.Label(root, text='标签6', bg='black', width='20').grid(row=1,column=2,sticky=tk.W)
##columnspan合并列,rowspan合并行
l7 = tk.Label(root, text='标签7', bg='pink',width='62').grid(row=2,column=0,columnspan=3)
l9 = tk.Label(root, text='标签9', bg='pink',width='62').grid(row=3,column=0,columnspan=3)
l8 = tk.Label(root, text='标签8', bg='purple',width='62').grid(row=2,column=0,rowspan=2,columnspan=3)
root.mainloop()