[Tutor] creating a method name on the fly

wesley chun wescpy at gmail.com
Tue Aug 8 00:28:44 CEST 2006


> 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 :-)


on a separate but related tangent, wait till y'all see PFA (partial
function application) coming up in 2.5.  you can use PFAs to
"templatize" GUI development.  for example, if you want all the
buttons to have the similar look-n-feel except for perhaps the text,
you can do something like (here's another clip from Core Python,
Example 11.6, pfaGUI.py):

#!/usr/bin/env python

from functools import partial
import Tkinter

root = Tkinter.Tk()
MyButton = partial(Tkinter.Button, root, fg='white', bg='blue')
b1 = MyButton(text='Button 1')
b2 = MyButton(text='Button 2')
qb = MyButton(text='QUIT', bg='red', command=root.quit)
b1.pack()
b2.pack()
qb.pack(fill=Tkinter.X, expand=True)
root.title('PFAs!')
root.mainloop()

"MyButton" contains all the common stuff for all buttons while the
others can take the defaults or override them! it sure looks cleaner
than having lots of duplicated code:

b1 = Tkinter.Button(root, fg='white', bg='blue', text='Button 1')
b2 = Tkinter.Button(root, fg='white', bg='blue', text='Button 2')
qb = Tkinter.Button(root, fg='white', text='QUIT', bg='red', command=root.quit)

cheers,
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
    http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com


More information about the Tutor mailing list