tkinter reading checkbutton values added through a for loop tkinter reading checkbutton values added through a for loop tkinter tkinter

tkinter reading checkbutton values added through a for loop


You could create a dictionary and have each key be the Checkbutton's label,
and have the value be the state "Control Variable".
Then you would check the state with the Control Variable's get() method as shown in the example below.

import tkinter as tkclass GUI(tk.Tk):    def __init__(self):        tk.Tk.__init__(self)        self.buttonDic = {        'Brown Rice':0,        'Banzai Veg':0,        'Red Cabbage':0,        'Black Beans':0        }        for key in self.buttonDic:            self.buttonDic[key] = tk.IntVar()            aCheckButton = tk.Checkbutton(self, text=key,                                            variable=self.buttonDic[key])            aCheckButton.grid(sticky='w')        submitButton = tk.Button(self, text="Submit",                                        command=self.query_checkbuttons)        submitButton.grid()    def query_checkbuttons(self):        for key, value in self.buttonDic.items():            state = value.get()            if state != 0:                print(key)                self.buttonDic[key].set(0)gui = GUI()gui.mainloop()

This approach allows you to create and analyze the Checkbuttons with one dictionary.
Note the use of items() in for key, value in self.buttonDic.items():
which is needed to prevent:
ValueError: too many values to unpack

More information on the Checkbutton widget and it's variable can be found: here


I'm going to include my first attempt which was based on
the Checkbutton widget's onvalue and offvalue,
in case it helps someone understand Control Variables a bit more.

import tkinter as tkclass GUI(tk.Tk):    def __init__(self):        tk.Tk.__init__(self)        self.bRiceV = tk.StringVar()        bRice = tk.Checkbutton(self, text="Brown Rice",variable=self.bRiceV,                                    onvalue="Brown Rice", offvalue="Off")        bRice.pack()        self.bVegV = tk.StringVar()        bVeg = tk.Checkbutton(self, text="Banzai Veg",variable=self.bVegV,                                    onvalue="Banzai Veg", offvalue="Off")        bVeg.pack()        self.varList = [self.bRiceV, self.bVegV]        submitButton = tk.Button(self, text="Submit",                                command=self.query_checkbuttons)        submitButton.pack()    def query_checkbuttons(self):        for var in self.varList:            value = var.get()            if value != 'Off':                print(value)                var.set('Off')gui = GUI()gui.mainloop()