I have created the following checkbox popup in Python 3.5 using tkinter (see image) with the following code:
from tkinter import *
class Checkbar(Frame):
def __init__(self, parent=None, picks=[], side=LEFT, anchor=W):
Frame.__init__(self, parent)
self.vars = []
for pick in picks:
var = IntVar()
chk = Checkbutton(self, text=pick, variable=var)
chk.pack(side=side, anchor=anchor, expand=YES)
self.vars.append(var)
def state(self):
return map((lambda var: var.get()), self.vars)
if __name__ == '__main__':
root = Tk()
lng = Checkbar(root, ['DerVar1', 'DerVar2', 'DerVar3', 'DerVar4', 'DerVar5', 'DerVar6', 'DerVar7', 'DerVar8'])
tgl = Checkbar(root, ['DerVar9','DerVar10', 'DerVar11', 'DerVar12', 'DerVar13', 'DerVar14'])
lng.pack(side=TOP, fill=X)
tgl.pack(side=LEFT)
lng.config(relief=GROOVE, bd=2)
def allstates():
print(list(lng.state()), list(tgl.state()))
Button(root, text='Quit', command=root.quit).pack(side=RIGHT)
Button(root, text='Run', command=allstates).pack(side=RIGHT)
root.mainloop()
As you can see I have checked 'DerVar2' and DerVar3'. After I click run I get the following highlighted in yellow.
As you can see a 1 corresponds to a checkbox getting checked.
the variable 'lng' is a checkbar object. I want to say if 'DerVar2' is checked, then print 'test' but can't get it to work.
This is the code I have tried and below is the error I get:
if lng[1] == 1:
print ('test')
TypeError: Can't convert 'int' object to str implicitly
The problem is that your
Checkbar
class has no__getitem__
method solng[1]
will trigger an error. To dolng[1] == 1
without errors, just add the following method to you rCheckbar
class:That way
lng[i]
will return the value of the i-thIntVar
of theCheckbar
You need to explicitly cast to the same types to compare. Try this:
or