Tkinter __call__
James Stroud
jstroud at mbi.ucla.edu
Fri Feb 16 05:56:02 EST 2007
Gigs_ wrote:
> from Tkinter import *
> from tkFileDialog import askopenfilename
> from tkColorChooser import askcolor
> from tkMessageBox import askquestion, showerror
> from tkSimpleDialog import askfloat
>
> demos = {
> 'Open': askopenfilename,
> 'Color': askcolor,
> 'Query': lambda: askquestion('Warning', 'You typed
> "..."\nConfirm?'),
> 'Error': lambda: showerror('Error!', "He's dead, Jim"),
> 'Input': lambda: askfloat('Entry', 'Enter credit card number')
> }
>
>
> class Demo(Frame):
> def __init__(self, parent=None):
> Frame.__init__(self, parent)
> self.pack()
> Label(self, text="Basic demos").pack()
> for (key, value) in demos.items():
> func = (lambda key=key: self.printit(key))
> Button(self, text=key, command=func).pack(side=TOP, fill=BOTH)
> def printit(self, name):
> print name, 'returns =>', demos[name]()
>
>
> I have tried but cant get it to work properly.
> I want to instead printit method to put __call__ and call it like that
> Can someone help me, please?
The code you have should work. My guess is that you don't understand
lambda and so you want to do it a "different" way, using a "callable"?
Well, that's what lambda does, it makes a callable object:
Python 2.5 (r25:51918, Sep 19 2006, 08:49:13)
[GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
py> key = 1
py> callable(lambda key=key: self.printit(key))
True
py> '__call__' in dir(lambda key=key: self.printit(key))
True
So the code you have already does what you want to do. Maybe understand
what you are studying before you reinvent the wheel--you will save
yourself a lot of frustration.
James
More information about the Python-list
mailing list