最简单的CheckButton多选类
import tkinter as tk #checkButton的内容,多选 root = tk.Tk() v = tk.IntVar()#装整形变量的 #variable:表示是否选中 v:选中为1,否则为0 c = tk.Checkbutton(root,text='测试一下',variable=v)#是一个选项框,前面有小勾 c.pack()#自动对齐 l = tk.Label(root,textvariable=v)#显示下面的0和1 l.pack() tk.mainloop()
用for循环表示
import tkinter as tk root = tk.Tk() GIRLS =['西施','貂蝉','王昭君','杨玉环'] v = [] for girl in GIRLS:#显示四大美女的显示框 v.append(tk.IntVar()) #variable:把变量放到最后一个 , b = tk.Checkbutton(root,text=girl,variable = v[-1]) b.pack(side = tk.LEFT) for each in v:#显示状态的框 l = tk.Label(root,textvariable=each) l.pack(side = tk.LEFT) tk.mainloop()
RadioButton 单选
import tkinter as tk root = tk.Tk() v = tk.IntVar() #Radiobutto是单选框,只能选中一个 #选中哪一个按钮,会把value的值赋给v a1 = tk.Radiobutton(root,text="one",variable=v,value=1) a1.pack(anchor=tk.W)#向西(west)对齐,即向左对齐 a2 = tk.Radiobutton(root,text="two",variable=v,value=2) a2.pack(anchor=tk.W) a3 = tk.Radiobutton(root,text="three",variable=v,value=3) a3.pack(anchor=tk.W) #显示v的值 l = tk.Label(root,textvariable=v) l.pack(anchor= tk.W) tk.mainloop()
采用for循环将其整合
import tkinter as tk root = tk.Tk() LANGS = [("python",1),("C",2),("Java",3),("Lua",4)] v = tk.IntVar() v.set(1)#把v的值设置为1 for lang,num in LANGS: #选中后 把num的值赋给 variable b = tk.Radiobutton(root,text=lang,variable = v ,value =num) b.pack(anchor = tk.W) l = tk.Label(root,textvariable=v)#显示标签 l.pack(side=tk.LEFT) tk.mainloop()
LabelFrame框架
import tkinter as tk #标签框架 root = tk.Tk() #新建标签框架 group = tk.LabelFrame(root,text="最好的语言是?") group.pack(padx=10,pady=10) LANGS = [("python",1),("C",2),("Java",3),("Lua",4)] v = tk.IntVar() for lang,num in LANGS: #选中后 把num的值赋给 variable b = tk.Radiobutton(group,text=lang,variable = v ,value =num) b.pack(anchor = tk.W) l = tk.Label(root,textvariable=v)#显示标签 l.pack(side=tk.LEFT) tk.mainloop()