从列表中创建多个复选框并获取所有值 [英] Create multiple checkboxes from a list and get all values

查看:146
本文介绍了从列表中创建多个复选框并获取所有值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to generate multiple checkboxes from a large list, and get all the values.

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

Here is my code so far (the list could be much larger):

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()

这可以按预期工作,但是当列表很大时,似乎不必将所有内容都写出来。

This works as intended but when it is a much larger list it seems unnecessary to write all of this out.

是否有办法仅通过遍历字符串列表来创建复选框/复选框(然后获取其值)?

Is there a way to create the checkboxes/checkbuttons (and then get their values) solely by iterating through the list of strings?

推荐答案

是的。您将需要将数据存储在某个地方。我建议做一本字典。

Yes. You will need to store the data somewhere. I suggest making a dictionary.

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()

这篇关于从列表中创建多个复选框并获取所有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆