How to get the state of multiple Checkbuttons in Tkinter? How to get the state of multiple Checkbuttons in Tkinter? tkinter tkinter

How to get the state of multiple Checkbuttons in Tkinter?


Your CheckButton command is executing the callback because that's what you are telling it to do. The command is supposed to be a reference to a function that tkinter can execute when the checkbutton is clicked. Tkinter passes the event object to the callback function. See this Effbot tutorial, but it looks like you are trying to implement their pattern already. You can get a reference to the checkbutton from the event.widget attribute as explained here. Finally, you need to attach your variable to "self" if you want to refer to it in the callback.

def relist(self):    self.text.delete(1.0,END)           p = subprocess.Popen (['ls', '/dev/'], stdout = subprocess.PIPE)           lst = p.communicate()[0].split('\n')           print lst           self.var = tk.IntVar()    for item in lst:                   cb = tk.Checkbutton(text="/dev/%s" % item, variable=self.var, command=self.myCallback)        self.text.window_create("end", window=cb)             self.text.insert("end", "\n") # to force one checkbox per linedef myCallback(self,event):    var = self.var.get()    print ("var is %s", str(var))


I think what you have asked for can be derived from here.

For each item in lst it must be previously created different IntVar() variable, just to indicate independent state of each checkbox.I do not see other way than to create them manually (I assume you don't have hundred of checkboxes).I will re-use the code from this answer and do the following:

def relist(self):    self.text.delete(1.0,END)           p = subprocess.Popen (['ls', '/dev/'], stdout = subprocess.PIPE)           lst = p.communicate()[0].split('\n')           print lst           self.var1 = tk.IntVar()    self.var2 = tk.IntVar()    self.var3 = tk.IntVar()    .    .    .     vars = [self.var1,self.var2,self.var3,...]    for item, var in zip(self.lst, vars):                   cb = tk.Checkbutton(text="/dev/%s" % item, variable=var, command= lambda: self.myCallback(var))        self.text.window_create("end", window=cb)             self.text.insert("end", "\n") # to force one checkbox per linedef myCallback(self,event,var):    each_var = var.get()    print ("var is %s", str(each_var))


I had the same issue. Try this one:

cb = tk.Checkbutton(text="/dev/%s" % item, variable=v, command=lambda: self.cb(index))

If you pass method as lambda function it executes the method on every change of the variable.