[Tutor] creating a method name on the fly

John Fouhy john at fouhy.net
Mon Aug 7 23:50:14 CEST 2006


On 08/08/06, Alan Gauld <alan.gauld at freenet.co.uk> wrote:
> Why not just add the buttons to a list as you create them then
> iterate over the list? Or better still use a dictionary with the name
> as key.

You can do nice things with tuples.

A simple example would be:

# (label, callback)
buttons = [('OK', self.OnOk), ('Cancel', self.OnCancel)]

for label, callback in buttons:
    b = Button(self, label=label, ...)
    # place b in your GUI
    b.Bind(..., self.OnCancel)

Obviously, the exact syntax and stuffw ill depend on the GUI toolkit
you are using.

Also you can put more information in your data structure if you want
(eg, information on placing the button, styles for the button, etc).
And, if you need to save the Button objects themselves, you could add
them to a dict in the body of the loop:

self.buttons = {}
for label, callback in buttons:
    # ...
    self.buttons[label] = b

It means that all the information about your GUI is brought together
in one place where it's easy to see, and all the mechanical work is
pushed off to one side :-)

-- 
John.


More information about the Tutor mailing list