Creating a function to make checkbutton with information from a list?

Thomas Jansson tjansson60 at gmail.com
Mon May 14 17:13:50 EDT 2007


On 13 Maj, 08:45, Peter Otten <__pete... at web.de> wrote:
> Thomas Jansson wrote:
> > Dear all
>
> > I am writing a program with tkinter where I have to create a lot of
> > checkbuttons. They should have the same format but should have
> > different names. My intention is to run the functions and the create
> > all the buttons with the names from the list.
>
> > I now the lines below doesn't work, but this is what I have so far. I
> > don't really know how call the element in the dict use in the for
> > loop. I tried to call +'item'+ but this doesn't work.
>
> > def create_checkbox(self):
> >    self.checkbutton = ["LNCOL", "LFORM", "LPOT", "LGRID",  "LERR",
> > "LCOMP"]
> >    for item in self.checkbutton:
> >       self.+'item'+Checkbutton = Chekcbutton(frame, onvalue='t',
> > offvalue='f', variable=self.+'item'+)
> >       self.+'item'+Checkbutton.grid()
>
> > How should I do this?
>
> You /could/ use setattr()/getattr(), but for a clean design putting the
> buttons (or associated variables) into a dictionary is preferrable.
>
> def create_checkbuttons(self):
>     button_names = ["LNCOL", "LFORM", "LPOT", "LGRID",  "LERR", "LCOMP"]
>     self.cbvalues = {}
>     for row, name in enumerate(button_names):
>         v = self.cbvalues[name] = IntVar()
>         cb = Checkbutton(self.frame, variable=v)
>         label = Label(self.frame, text=name)
>         cb.grid(row=row, column=0)
>         label.grid(row=row, column=1)
>
> You can then find out a checkbutton's state with
>
> self.cbvalues[name].get()
>
> Peter

Both of you for your answers I ended up using the last one since it
seemed least complicated to new python programmer as my self. In the
case that anyone should ever read the post again and would like to see
what I ended up with:

self.button_names = ["LPOT", "LNCOL", "LFORM", "LGRID", "LERR",
"LCOMP", "LMAP", "LPUNCH", "LMEAN"]
button_state =      ["t"    , "t"    , "t"   , "t"    , "f"   ,
"f"    , "f"   , "t"     , "f"    ]
self.cbvalues = {}
for row, name in enumerate(self.button_names):
  v = self.cbvalues[name] = StringVar() # It is a string variable so,
t or f can be store here
  self.cb = Checkbutton(frame, onvalue="t", offvalue="f", variable=v)
  label = Label(frame, text=name)
  label.grid(row=row+15, column=0, sticky=W)
  self.cb.grid(row=row+15, column=1, sticky=W)
  if button_state[row] == "t":
    self.cb.select()
  else:
    self.cb.deselect()

Kind regards
Thomas Jansson




More information about the Python-list mailing list