从列表中创建多个复选框并获取所有值

时间:2018-04-26 17:09:11

标签: python checkbox tkinter

我想从大型列表中生成多个复选框,并获取所有值。

到目前为止,这是我的代码(列表可能更大):

from Tkinter import *

def print_ingredients(*args):
   values = [('cheese',cheese.get()),('ham',ham.get()),('pickle',pickle.get()),('mustard',mustard.get()),('lettuce',lettuce.get())]
   print values

lst = ['cheese','ham','pickle','mustard','lettuce']

top = Tk()

mb=  Menubutton ( top, text="Ingredients", relief=RAISED )
mb.grid()
mb.menu  =  Menu ( mb, tearoff = 0 )
mb["menu"]  =  mb.menu

cheese=IntVar()
ham=IntVar()
pickle=IntVar()
mustard=IntVar()
lettuce=IntVar()

l = mb.menu.add_checkbutton(label="cheese", variable = cheese)
l = mb.menu.add_checkbutton(label="ham", variable = ham)
l = mb.menu.add_checkbutton(label="pickle", variable = pickle)
l = mb.menu.add_checkbutton(label="mustard", variable = mustard)
l = mb.menu.add_checkbutton(label="lettuce", variable = lettuce)

btn = Button(top, text="Print", command=print_ingredients)
btn.pack()

mb.pack()

top.mainloop()

这可以按预期工作,但当它是一个更大的列表时,似乎没有必要写出所有这些。

有没有办法通过迭代字符串列表来创建复选框/复选框(然后获取它们的值)?

1 个答案:

答案 0 :(得分:2)

是。您需要将数据存储在某处。我建议写一本字典。

from Tkinter import *

INGREDIENTS = ['cheese','ham','pickle','mustard','lettuce']

def print_ingredients(*args):
   values = [(ingredient, var.get()) for ingredient, var in data.items()]
   print values

data = {} # dictionary to store all the IntVars

top = Tk()

mb=  Menubutton ( top, text="Ingredients", relief=RAISED )
mb.menu  =  Menu ( mb, tearoff = 0 )
mb["menu"]  =  mb.menu

for ingredient in INGREDIENTS:
    var = IntVar()
    mb.menu.add_checkbutton(label=ingredient, variable=var)
    data[ingredient] = var # add IntVar to the dictionary

btn = Button(top, text="Print", command=print_ingredients)
btn.pack()

mb.pack()

top.mainloop()