Reputation: 285
I'm using python 2.7 with Tkinter (new to Tkinter:)) I have UI with list of 20 checkboxes once I click on one checkbox, all checkboxes are being checked, instead of one. In code below you'll see 2 line (once with #) with # -when click on checkbox only one is checked which is ok without # -when click on one, all are being checked The problem is that I want to know the status of each checkbox if checed or not and I have to define var=Intvar in order to "get" it status Any suggestion? Thanks in advance Below is relevant def
def suites_checkbox_create(self):
ExcelWorkBook1 = open_workbook(config.UI_Suites_Location + 'STD_SUITES.xlsx', on_demand=True)
First_Sheet1 = ExcelWorkBook1.sheet_by_index(0)
plushight = 110
suitesList=[]
self.CheckboxList=[]
for name in (First_Sheet1._cell_values):
if name[3] == "General Name":
continue
else:
suitesList.append(name[3])
for index, name in enumerate(suitesList):
self.var=IntVar
#self.CheckboxList.append(Checkbutton(self.app, text=name)) # using this, i can check once checkbox a time
self.CheckboxList.append(Checkbutton(self.app, text=name, variable=self.var)) # with this, once i check once checkbox, all checkboxes(20) are bing checked
self.CheckboxList[index].place(y=plushight)
plushight += 20
Upvotes: 0
Views: 2479
Reputation: 4730
The reason this happens is because you've given all of your Checkbutton
widgets the same variable for their variable
attribute.
Meaning that as soon as one of the Checkbutton
widgets is ticked self.var
is given a value of 1
which means that all of the Checkbutton
widgets have a value of 1
which equates to them having been selected.
In short, whenever one is ticked it updates the value of all the other's because they have the same variable used to store their value.
See this in the example below:
from tkinter import *
root = Tk()
var = IntVar()
for i in range(10):
Checkbutton(root, text="Option "+str(i), variable = var).pack()
root.mainloop()
To resolve this you need to use a different variable for each Checkbutton
, like the below:
from tkinter import *
root = Tk()
var = []
for i in range(10):
var.append(IntVar())
Checkbutton(root, text="Option "+str(i), variable = var[i]).pack()
root.mainloop()
Upvotes: 3