Menus with Tkinter ??

David Bolen db3l at fitlinxx.com
Mon Sep 11 18:08:36 EDT 2000


isard at localhost.localdomain (Carles =?iso-8859-1?Q?Sadurn=ED?= Anguita) writes:

> I'm learning python and tkinter and I've found an amazing "problem". Why
> does this code work

I don't know enough Tk to help you with passing in parameters to be
supplied to a callback routine (what I'm guessing you are trying to
achieve), but I can epxlain why you are seeing the behavior you are.

In your first case, the lines

> menuarxiu.add_command(label="Ah!", command=ah)
> menuarxiu.add_command(label="Oh!", command=oh)

set the value of the command parameter to the function object for each
of your functions.  This is a simple assignment, as "ah" and "oh" are
the labels for the functions.

But in your second case:

> menuarxiu.add_command(label="Ah!", command=ah(0))
> menuarxiu.add_command(label="Oh!", command=ah(1))

You are actually calling the function "ah", and then setting the
command parameter to the result of the function (None in this case).
The output you see is from the print in the function running as it is
called in order to determine the value to use for the command
parameter.  And since your "ah" function doesn't return a result, the
above is equivalent to setting command to "None" in each case, aside
from the function call itself.

For example, from the interactive prompt:

    Define the function:

    >>> def func():
    ...   print "hello"
    ...

    Note the difference between referring to the function and calling it:

    >>> func
    <function func at 7f6370>
    >>> func()
    hello

    Assigning to a new label is similar to the 'command' parameter:
    >>> foo=func

    Once assigned, it can be called (this is how Tk does the callback):
    >>> foo()
    hello

    But assigning the result of calling the function is different, and
    ends up with the assigned name having the result (None) of the
    function:
    >>> foo=func()
    hello
    >>> print foo
    None

--
-- David
-- 
/-----------------------------------------------------------------------\
 \               David Bolen            \   E-mail: db3l at fitlinxx.com  /
  |             FitLinxx, Inc.            \  Phone: (203) 708-5192    |
 /  860 Canal Street, Stamford, CT  06902   \  Fax: (203) 316-5150     \
\-----------------------------------------------------------------------/



More information about the Python-list mailing list