使用tkinter创建复选框
我需要一些关于编写tkinter复选框的帮助。
我有一个复选按钮,如果我选择它,会启用很多其他的复选框。下面是选择第一个复选框后执行的函数:
def enable_():
# Global variables
global var
# If Single test
if (var.get()==1):
Label (text='Select The Test To Be Executed').grid(row=7,column=1)
L11 = Label ().grid(row=9,column=1)
row_me =9
col_me =0
test_name_backup = test_name
for checkBoxName in test_name:
row_me = row_me+1
chk_bx = Checkbutton(root, text=checkBoxName, variable =checkBoxName, \
onvalue = 1, offvalue = 0, height=1, command=box_select(checkBoxName), \
width = 20)
chk_bx.grid(row = row_me, column = col_me)
if (row_me == 20):
row_me = 9
col_me = col_me+1
我这里有两个问题。
如何删除动态创建的复选框(chk_bx)?我的意思是,如果我选择了最初的复选框,它会启用很多其他的复选框;如果我取消选择第一个复选框,应该把最初创建的复选框删除掉。
我怎么能获取动态创建的复选框的值,是“选中”还是“未选中”?
1 个回答
1
1. 如何删除动态创建的复选框?
只需要把所有的复选框放到一个列表里,这样在需要的时候就可以对它们调用 destroy()
方法来删除它们:
def remove_checkbuttons():
# Remove the checkbuttons you want
for chk_bx in checkbuttons:
chk_bx.destroy()
def create_checkbutton(name):
return Checkbutton(root, text=name, command=lambda: box_select(name),
onvalue=1, offvalue=0, height=1, width=20)
#...
checkbuttons = [create_checkbutton(name) for name in test_name]
2. 我怎么才能获取动态创建的复选框的值“选中/未选中”?
你需要创建一个 Tkinter 的 IntVar
,这个东西用来存储复选框的状态值,也就是选中时的值和未选中时的值。你还需要跟踪这个对象,但不需要再创建一个新的列表,因为你可以把它和对应的复选框关联起来:
def printcheckbuttons():
for chk_bx in checkbuttons:
print chk_bx.var.get()
def create_checkbutton(name):
var = IntVar()
cb = Checkbutton(root, variable=var, ...)
cb.var = var
return cb