Create multiple checkboxes from a list and get all values

旧时模样 提交于 2019-12-24 16:43:22

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/50048561/create-multiple-checkboxes-from-a-list-and-get-all-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!