0

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()  

enter image description here

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.
enter image description here

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

2 Answers 2

1

The problem is that your Checkbar class has no __getitem__ method so lng[1] will trigger an error. To do lng[1] == 1 without errors, just add the following method to you rCheckbar class:

def __getitem__(self, key):
    return self.vars[key].get()

That way lng[i] will return the value of the i-th IntVar of the Checkbar

Sign up to request clarification or add additional context in comments.

Comments

0

You need to explicitly cast to the same types to compare. Try this:

 if int(lng[1]) == 1:
    print ('test')

or

if lng[1] == str(1):
    print ('test')

2 Comments

thanks for the quick response; I get the same exact error when I try either option listed above. The error is: TypeError: Can't convert 'int' object to str implicitly
Yes - you have an issue in your Checkbar class - add a get_item method as described above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.