[Tutor] Lots of variables

Kent Johnson kent37 at tds.net
Sat Aug 6 19:47:57 CEST 2005

Øyvind wrote:
> Hello.
> I am trying to write a gui that has a lot of checkboxes. It is over 200
> different ones. I use a for statement to generate:
>         ver = 200
>         for i in ['Car','House','Boat','Plane']:
>             self.fra26_che01p = Checkbutton (self.fra26)
>             self.fra26_che01p.place(in_=self.fra26,x=5,y=ver)
>             self.fra26_che01p.configure(text=i)
>             self.getattr(self,i)1 = IntVar()
>             self.fra26_che01p.configure(variable=getattr(self,i))
>             self.fra26_che01v = Checkbutton (self.fra26)
>             self.fra26_che01v.place(in_=self.fra26,x=70,y=ver)
>             #self.fra26_che01v.configure(text="1p")
>             self.getattr(self,i)2 = IntVar()
>             self.fra26_che01v.configure(variable=getattr(self,i))
>             ver = ver + 17
> The variable does not work for obvious reasons. I need to change variable
> for each new creation. If I had made the variables manually, I would have
> written (variable=self.car1)/(variable=self.car2) and so forth. Is there
> some way I can make lots of variables without declaring them up front?

The usual way to do this is to keep a dictionary mapping the 'variable' names to the values, or maybe just a list of the values. Since you access the checkbuttons through IntVars you may not need to keep a reference to the button itself. So maybe something like this:

        self.vars = {}
        ver = 200
        for i in ['Car','House','Boat','Plane']:
            check1 = Checkbutton (self.fra26)
            var1 = self.vars[i+'1'] = IntVar()
            check1 .configure(variable=var1)
            check2 = Checkbutton (self.fra26)
            var2 = self.vars[i+'2'] = IntVar()
            ver = ver + 17

Now self.vars will have entries for 'Car1', 'Car2', etc. whose values will be the corresponding IntVars.


More information about the Tutor mailing list