tkinter中布局pack、place和grid(八)
tkinter中布局pack、place和grid
pack布局
1 import tkinter
2
3 wuya = tkinter.Tk()
4 wuya.title("wuya")
5 wuya.geometry("300x200+10+20")
6
7
8 # fill控制填充方式
9 lb1 = tkinter.Label(wuya,
10 text='wuya good good study',
11 bg='red',
12 )
13 lb1.pack(fill=tkinter.X)
14
15
16 # padding 控制边距,如果不设置则默认为0
17 # padx,设置x方向的外边距,pady设置y方向的外边距
18 lb2 = tkinter.Label(wuya,
19 text='wuyaa',
20 bg='green',
21 )
22 lb2.pack(fill=tkinter.X,padx=10,pady=3)
23 # ipadx,设置x方向的外边距,pady设置y方向的外边距
24 lb3 = tkinter.Label(wuya,
25 text='wuyab',
26 bg='blue',
27 )
28 lb3.pack(fill=tkinter.X,ipadx=10,ipady=3)
29
30
31 # side 为依次放置
32 lb4 = tkinter.Label(wuya,
33 text='wuya1',
34 bg='yellow',
35 )
36 lb4.pack(side='left')
37 lb4 = tkinter.Label(wuya,
38 text='wuya2',
39 bg='pink',
40 )
41 lb4.pack(side='left',padx=3)
42
43 wuya.mainloop()
结果:
place布局
比较好理解,直接以所在的窗口的左上角为(0,0)开始计算,x为横向的尺寸,y为纵向的尺寸,然后设置显示的宽和高
1 import tkinter
2
3 wuya = tkinter.Tk()
4 wuya.title("wuya")
5 wuya.geometry("300x200+10+20")
6
43 lb1 = tkinter.Label(wuya,
44 text='wuya good good study',
45 bg='red',
46 )
47 lb1.place(x=10,y=10,width=200,height=120)
48
49 lb2 = tkinter.Label(wuya,
50 text='wuya good good study',
51 bg='green',
52 )
53 lb2.place(x=220,y=140,width=20,height=12)
54
55 wuya.mainloop()
结果为:
grid布局
1 import tkinter
2
3 wuya = tkinter.Tk()
4 wuya.title("wuya")
5 wuya.geometry("300x200+10+20")
6
7 citys = {'001':'beijing',
8 '002':'shanghai',
9 '111':'tianjing',
10 '212':'xizang'}
11 i = 0
12 for item in citys:
13 lb1 = tkinter.Label(wuya, text=item,relief=tkinter.RIDGE,width=15,fg='blue')
14 lb1.grid(row=i,column=0)
15 lb2 = tkinter.Label(wuya,text=citys[item],relief=tkinter.SUNKEN,width=15,fg='red')
16 lb2.grid(row=i,column=1)
17 i = i + 1
18
19 wuya.mainloop()
row表示行,第几行。column表示列,第几列。计算的时候都是从0开始的
结果为: