Search code examples
pythonpython-2.7checkboxwxpython

How to record multiple checkboxes in wxPython?


I am trying to get my program to record if the user clicked on checkbox(es) so I know what things to delete. The problem is that I don't have all the variables names for all the checkboxes so I can't just do GetValue(). In the code below, I have a set number of things but in the actual program, it pulls user info from file.

import wx
class supper(wx.Frame):
    def __init__(self,parent,id):
        wx.Frame.__init__(self,parent,id,'Delete Stocks',size=(300,300))
        nexus=wx.Panel(self)
        again=30
        newfp='GOOG AAPL'.split()
        #Need to see if user checked box and which one
        for i in newfp:
            self.checkbox=(wx.CheckBox(nexus,-1,i,(30,again),(160,-1)))
            self.Bind(wx.EVT_CHECKBOX, self.lol,self.checkbox)
            again+=30
        anothercancel=wx.Button(nexus,label='Cancel',pos=(50,250),size=(60,40))
        self.Bind(wx.EVT_BUTTON,self.acancel,anothercancel)
        anotherok=wx.Button(nexus,label='OK',pos=(200,250),size=(60,40))
        self.Bind(wx.EVT_BUTTON,self.okalready,anotherok)
    def acancel(self,event):
        self.Destroy()
    #Couldn't figure out how to see what check was clicked
    def okalready(self,event):
        for i in newfp:
            valuechecker=self.checkbox.GetValue()
            if self.checkbox.Get()==True:
                print 'You clicked this %s one'%i
        self.Destroy()
    def lol(self,event):
        pass
if __name__=='__main__':
    ok=wx.PySimpleApp()
    people=supper(parent=None,id=-1)
    people.Show()
    ok.MainLoop()

This isn't the whole thing so there might be a variable that is not defined here. Thanks in advance! Look forward to the answers!


Solution

  • just keep them in a list ...

    self.checkboxes = []
    for i in newfp:
            self.checkboxes.append(wx.CheckBox(nexus,-1,i,(30,again),(160,-1)))
            self.checkboxes[-1].Bind(wx.EVT_CHECKBOX, self.lol)
            again+=30
    

    then to check which boxes are checked when you click ok you can use this

    def okalready(self,event):
        for i,cb in enumerate(self.checkboxes):
           print "CB:%d = %s"%(i,cb.GetValue())
        print "Checked:",[cb.GetLabel() for cb in self.checkboxes if cb.GetValue()]
        self.Destroy()