jeudi 26 avril 2018

Create multiple checkboxes from a list and get all values

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?




Aucun commentaire:

Enregistrer un commentaire