Is it possible to call a function from a Tkinter widget.bind and include args???
Eric Brunel
eric.brunel at pragmadev.com
Tue Feb 12 05:03:19 EST 2002
Hi,
G. Willoughby wrote:
> Is it possible to call a function from a Tkinter widget.bind and include
> args???
> i.e. i want to do something like this:
>
> def printButtonAndCoords(event, button):
> print "you rolled over %s and coords are %d:%d" % button, event.x,
> eventy
>
> Button1.bind("<Enter>", printButtonAndCoords("button1"))
> Button2.bind("<Enter>", printButtonAndCoords("button2"))
>
> is this possible???
Since you didn't mention your Python version, maybe the lambda stuff
provided by Martin and Fredrik won't work (with pre-2.0 versions, the
lambda may not have the printButtonAndCoords function in its namespace,
isn't it?).
So here is another solution I used quite a lot. with pre-2.0 Python It
involves the creation of a callback class:
class GenericCallback:
def __init__(self, callback, *firstArgs):
self.__callback = callback
self.__firstArgs = firstArgs
def __call__(self, *lastArgs):
apply(self.__callback, self.__firstArgs + lastArgs)
Then you make your binding like follows:
Button1.bind("<Enter>", GenericCallback(printButtonAndCoords, "button1"))
Your printButtonAndCoords function should then take the string as first
argument and the Tkinter event as second. The binding will "call" the
instance of GenericCallback, i.e. call its __call__ method, which will in
turn call printButtonAndCoords with the arguments provided in the
constructor, then in the actual call.
The GenericCallback class is also generic enough to have many other uses
(in fact everywhere you must provide a function).
HTH
- eric -
More information about the Python-list
mailing list