Some basic questions about Tkinter (probably v easy for experts!)

Fredrik Lundh fredrik at pythonware.com
Thu Feb 8 13:33:04 EST 2001


Martyn Quick wrote:
> I've realized one point that was confusing me.
> When I use sys.exit to finish a python script I would type
>
> sys.exit()
>
> but in the above you use  exit  rather than  exit().
> Is it generally the case that you don't use the brackets in the
> comannd=...  part?

not unless you want to *call* the function.

> (Sorry if this is easily to be found in the Introduction document!)

it's a Python thing, not a Tkinter thing.  functions (and
methods, classes, modules, etc) are objects -- just like
integers, strings, and other simple types:

to call an object, add parentheses:

>>> import sys
>>> sys # this name points to a module object
<module 'sys' (built-in)>
>>> sys.exit # this name points to a function
<built-in function exit>
>>> x = sys.exit # add another name for the same function
>>> x
<built-in function exit>
>>> sys.exit() # call the function
$

(after the assignment, you could also have typed x())

so in the following statement, we're passing the *function*
itself as the command value:

    widget.config(command=sys.exit)

while in the following statement, we're *calling* the function.
if the function returns (sys.exit() doesn't), the return value is
passed on to the widget:

    widget.config(command=sys.exit())

(functions can return function objects, so this might actually
make sense in some cases.  but not for sys.exit() ;-)

> Presumably this means that I can't use a command which relies on
> parameters?

not directly -- there's something called lambdas (in Python, not
in Tkinter), but it's usually better to use a plain function:

    def myfunc():
        otherfunc(1, 2, 3)

    b = Button(master, command=myfunc)

Cheers /F





More information about the Python-list mailing list