[Tutor] Tkinter wierdness
Magnus Lycka
magnus@thinkware.se
Tue Dec 10 17:37:02 2002
At 12:42 2002-12-10 -0600, Isaac Hall wrote:
>P.S. the inevitable follow-up question: why must this be done? if I wish
>to call a function with some arguments, how is this done?
Because "command=function" means "function is the command you should
run". "command=function()" means "The result value from function is
the command you should run".
Look here:
>>> def hw(aString="world"):
... return "Hello %s" % aString
...
>>> print hw()
Hello world
>>> print hw
<function hw at 0x015E9900>
>>> command = hw
>>> command
<function hw at 0x015E9900>
>>> command()
'Hello world'
>>> command('Moon')
'Hello Moon'
>>> command = hw()
>>> command
'Hello world'
>>> command()
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
TypeError: 'str' object is not callable
See the difference? When you bind a command in Tkinter, you tell
the computer what to run at a later time. You must hand over something
that can run, right?
But look here!
>>> class hw:
... def __init__(self, greeting='hello'):
... self.greeting = greeting
... def __call__(self, who='world'):
... return "%s %s" % (self.greeting, who)
...
>>> command = hw('hi') # Run __init__
>>> command('moon') # Run __call__
'hi moon'
--
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/ mailto:magnus@thinkware.se