Python Form: Using TKinter --> run script based

2019-09-11 03:07发布

问题:

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

回答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



回答2:

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