tkinter中布局pack、place和grid
pack布局
import tkinter wuya = tkinter.Tk() wuya.title("wuya") wuya.geometry("300x200+10+20") # fill控制填充方式 lb1 = tkinter.Label(wuya, text='wuya good good study', bg='red', ) lb1.pack(fill=tkinter.X) # padding 控制边距,如果不设置则默认为0 # padx,设置x方向的外边距,pady设置y方向的外边距 lb2 = tkinter.Label(wuya, text='wuyaa', bg='green', ) lb2.pack(fill=tkinter.X,padx=10,pady=3) # ipadx,设置x方向的外边距,pady设置y方向的外边距 lb3 = tkinter.Label(wuya, text='wuyab', bg='blue', ) lb3.pack(fill=tkinter.X,ipadx=10,ipady=3) # side 为依次放置 lb4 = tkinter.Label(wuya, text='wuya1', bg='yellow', ) lb4.pack(side='left') lb4 = tkinter.Label(wuya, text='wuya2', bg='pink', ) lb4.pack(side='left',padx=3) wuya.mainloop()
结果:
place布局
比较好理解,直接以所在的窗口的左上角为(0,0)开始计算,x为横向的尺寸,y为纵向的尺寸,然后设置显示的宽和高
import tkinter wuya = tkinter.Tk() wuya.title("wuya") wuya.geometry("300x200+10+20") lb1 = tkinter.Label(wuya, text='wuya good good study', bg='red', ) lb1.place(x=10,y=10,width=200,height=120) lb2 = tkinter.Label(wuya, text='wuya good good study', bg='green', ) lb2.place(x=220,y=140,width=20,height=12) wuya.mainloop()
结果为:
grid布局
import tkinter wuya = tkinter.Tk() wuya.title("wuya") wuya.geometry("300x200+10+20") citys = {':'beijing', ':'shanghai', ':'tianjing', ':'xizang'} i = 0 for item in citys: lb1 = tkinter.Label(wuya, text=item,relief=tkinter.RIDGE,width=15,fg='blue') lb1.grid(row=i,column=0) lb2 = tkinter.Label(wuya,text=citys[item],relief=tkinter.SUNKEN,width=15,fg='red') lb2.grid(row=i,column=1) i = i + 1 wuya.mainloop()
row表示行,第几行。column表示列,第几列。计算的时候都是从0开始的
结果为: