[Tutor] creating a method name on the fly

John Fouhy john at fouhy.net
Tue Aug 8 00:44:58 CEST 2006


On 08/08/06, wesley chun <wescpy at gmail.com> wrote:
> 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)
>
> "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)

I sometimes do this:

buttonOpts = { 'fg':'white', 'bg':'blue' }
packOpts = { I forget :-) }
buttons = [('Button 1', None), ('Button 2', None), ('Button 3', root.quit)]

for label, callback in buttons:
    b = Tkinter.Button(label, command=callback, **buttonOpts)
    b.pack(**packOpts)

But, yeah, partial application will be cool :-)

-- 
John.


More information about the Tutor mailing list