Create multiple checkboxes from a list and get all values

后端 未结 1 1840
[愿得一人]
[愿得一人] 2021-01-27 01:06

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 Tkin         


        
相关标签:
1条回答
  • 2021-01-27 01:34

    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()
    
    0 讨论(0)
提交回复
热议问题