On May 12, 11:04 am, Thomas Jansson <[EMAIL PROTECTED]> 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?
>
> Kind regards
> Thomas Jansson

You can use exec("self." + name + " = " + value) to do what you want,
but then you need to exec() each time you want to access the
variable.  I think it is much better to create a class.

Here's what I came up with:

from Tkinter import *

class Window(Frame):
        def __init__(self, parent=None):
                Frame.__init__(self,parent=None)
                self.names = ["LNCOL", "LFORM", "LPOT", "LGRID",  "LERR", 
"LCOMP",
"Sean"]
                self.checkbuttons = []

                self.f = Frame(root)
                for name in self.names:
                        self.checkbuttons.append(CButton(parent=self.f, 
name=name,
default="f"))

                self.f.pack(side="top",padx=5, pady=5)


class CButton(object):
        def __init__(self, parent=None, name=None, default=None):
                self.name = name
                self.parent = parent
                self.variable = StringVar()
                self.variable.set(default)
                self.checkbutton = None
                self.create_checkbox(name)

        def create_checkbox(self,name):
                f = Frame(self.parent)
                Label(f, text=name).pack(side="left")
                self.checkbutton  = Checkbutton(f, onvalue='t', offvalue='f',
variable=self.variable)
                self.checkbutton.bind("<Button-1>", self.state_changed)
                self.pack()
                f.pack()

        def pack(self):
                self.checkbutton.pack()

        def state_changed(self, event=None):
                print "%s: %s" % (self.name, self.variable.get())

if __name__ == '__main__':
        root = Tk()
        Window().mainloop()

~Sean

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to