实例1:Checkbutton 组件
1 from tkinter import *
2
3 root = Tk()
4 #需要一个Tkinter变量,用于表示该按钮是否被选中
5 v = IntVar()
6 c = Checkbutton(root,text="测试一下",variable = v)
7
8 c.pack()
9 #如果被选中,那么变量v被赋值为1,否则为0
10 #可以用个Label标签动态地给大家展示:
11 lable = Label(root,textvariable = v)
12 lable.pack()
13
14 mainloop()
实例2:
1 from tkinter import *
2
3 root = Tk()
4
5 GIRLS = ["貂蝉","王昭君","西施","杨玉环"]
6 v = []
7 for girl in GIRLS:
8 v.append(girl)
9 c = Checkbutton(root,text = girl,variable = v[-1])#-1表示每次取v列表中最后一个元素,即刚加入的那个元素
10 c.pack(anchor = W)#W(western)向左对齐
11
12 mainloop()
实例3:Radiobutton 组件
1 from tkinter import *
2
3 root = Tk()
4
5 v = IntVar()#如果被选中,v被赋值为1,否则为0
6 Radiobutton(root,text = "One",variable = v,value = 1).pack(anchor = W)
7 #value表示第一个按钮被选中时,v的值赋值给variable
8
9 Radiobutton(root,text = "Two",variable = v,value = 2).pack(anchor = W)
10
11 Radiobutton(root,text = "Three",variable = v,value = 3).pack(anchor = W)
12
13 Radiobutton(root,text = "Four",variable = v,value = 4).pack(anchor = W)
14
15 mainloop()
实例4:循环处理
1 from tkinter import *
2
3 root = Tk()
4
5 LANGS = [
6 ("Python",1),
7 ("Perl",2),
8 ("Ruby",3),
9 ("Lua",4)]
10
11
12 v = IntVar()#如果被选中,v被赋值为1,否则为0
13 v.set(1)#将1设置为默认值
14 for lang,num in LANGS:
15 b= Radiobutton(root,text = lang,variable = v,value = num)
16 b.pack(anchor = W)
17 #value表示第一个按钮被选中时,v的值赋值给variable
18
19 mainloop()
实例5:改成按钮形式
1 from tkinter import *
2
3 root = Tk()
4
5 LANGS = [
6 ("Python",1),
7 ("Perl",2),
8 ("Ruby",3),
9 ("Lua",4)]
10
11
12 v = IntVar()#如果被选中,v被赋值为1,否则为0
13 v.set(1)#将1设置为默认值
14 for lang,num in LANGS:
15 b= Radiobutton(root,text = lang,variable = v,value = num,indicatoron = False)
16 b.pack(fill = X)#表示横向填充
17 #value表示第一个按钮被选中时,v的值赋值给variable
18
19 mainloop()
实例6:LabelFrame 组件
1 from tkinter import *
2
3 root = Tk()
4
5 group = LabelFrame(root,text = "最好的脚本语言是?",padx = 10,pady = 10)#按钮相对边框的偏移
6 group.pack(padx = 10,pady = 10)#框架相对边框的偏移
7
8 LANGS = [
9 ("Python",1),
10 ("Perl",2),
11 ("Ruby",3),
12 ("Lua",4)]
13
14
15 v = IntVar()#如果被选中,v被赋值为1,否则为0
16 v.set(1)#将1设置为默认值
17 for lang,num in LANGS:
18 b= Radiobutton(group,text = lang,variable = v,value = num,indicatoron = False)
19 b.pack(fill = X)
20 #value表示第一个按钮被选中时,v的值赋值给variable
21
22 mainloop()