Tkinter problem

Chad Netzer cnetzer at mail.arc.nasa.gov
Tue Oct 1 17:11:38 EDT 2002


On Tuesday 01 October 2002 13:23, Newt wrote:
> Hi,
>
> Can anyone explain why the following code runs strangely. When I run
> it, it seems as if the setrace routine is called regardless, even
> before the main form has been displayed.

That is because it does exactly what you told it to do.  You are 
calling the setrace function, rather than asking that it be used as a 
callback.  "setrace" is the function object, and can be used as a 
callback binding; setrace() is the called function, which returns the 
results of the call (in this case, the None object)

So, change this line:
listr.bind('<Button-1>',setrace(root, listr, lblr ))

to this:
listr.bind('<Button-1>',setrace_callback )

and introduce this new function which is called when the button is 
pressed, and then calls your function with the proper arguments:

def setrace_callback( *crap ):
    setrace( root, listr, lblr )
    return

Now, pressing Button-1 calls the 'setrace_callback' function (with some 
event handling arguments that you don't use; See Tk manual for more 
info), which then calls your 'setrace' function to do the work.

NOTE!!!  This only works as is because you are using globals (since 
your program is supplied is written outside of a class or function), 
and so 'setrace' can see these globals.  This is really bad form.  
Often, people would use a "lamda" anonymous function to bind up the 
arguments to 'setrace' at declaration time, or use a method called 
'currying' (which I prefer).  And if this all took place inside a 
class, your arguments could then be state variables.

See the ASPN Python Cookbook to learn more about how to "curry" in 
Python.  Or better yet, make this all a class, and bind a class method 
to the Button-1 press.

-- 

Chad Netzer
cnetzer at mail.arc.nasa.gov




More information about the Python-list mailing list