Python tkinter中的布局有
1.place
2.pack
3.grid
分别是绝对,流式和网格布局。
- Place布局,明确指定位置和大小
from tkinter import *
root = Tk()
# width x height + x_offset + y_offset:
root.geometry("180x200+30+30")
languages = ['Python', 'Groovy', 'C++', 'Java']
bg_colors = '#0c76b7,#f422d5,#03ca50,#faaed0'.split(',')
for i in range(len(languages)):
label = Label(root,
text=languages[i],
fg='White' if i <= 2 else 'Black',
bg=bg_colors[i])
label.place(x=20, y=30 + i * 30, width=120, height=25)
root.mainloop()

位置是相对于父容器的,拉伸窗口,位置大小不变。
- Pack布局
from tkinter import *
root = Tk()
root.geometry("300x400+300+100")
frame = Frame(root, relief=RAISED, borderwidth=1)
Label(frame, text="Red Sun", bg="red", fg="white").pack(fill=X,side=LEFT)
Label(frame, text="Green Grass", bg="green", fg="black").pack(fill=X,padx=10,ipady=10,side=LEFT)
Label(frame, text="Blue Sky", bg="blue", fg="white").pack(pady=10,side=RIGHT)
frame.pack(fill=BOTH)
frame2 = Frame(root)
frame2.pack(fill=BOTH, expand=True)
lbl3 = Label(frame2, text="Review", width=6)
lbl3.pack(side=LEFT, anchor=N, padx=5, pady=5)
txt = Text(frame2,height=5)
txt.pack(fill=BOTH, pady=5, padx=5, expand=True)
frame3 = Frame(root)
frame3.pack(fill=None, expand=FALSE)
closeButton = Button(root, text="Close")
closeButton.pack(side=RIGHT, padx=5, pady=5)
okButton = Button(root, text="OK")
okButton.pack(side=RIGHT)
mainloop()

pack布局本身很简单,fill指定分给它的空间有剩余时要不要扩展,expand指定窗口有多新空间时,要不要给它多余空间。anchor指定它比拥有的空间小时,上下左右与哪对齐。通常与Frame结合使用。
- Grid
from tkinter import *
frame = Frame()
frame.pack(fill=BOTH, expand=True)
frame.columnconfigure(1, weight=1)
colours = ['red','green','orange','white','yellow','blue']
entry = Entry(frame)
entry.grid(row=0, columnspan=2, sticky=W+E)
r = 1
for c in colours:
Label(frame,text=c, relief=RIDGE,width=15).grid(row=r,column=0)
Entry(frame,bg=c, relief=SUNKEN,width=10).grid(row=r,column=1)
r = r + 1
mainloop()

grid就是按行列布局,columnconfigure()中的weight使指定的列可以扩展,sticky指定与空间的哪边对齐。
网友评论