Is it possible to call a function from a Tkinter widget.bind and include args???

Fredrik Lundh fredrik at pythonware.com
Mon Feb 11 17:03:02 EST 2002


G. wrote:

> Button1.bind("<Enter>", printButtonAndCoords("button1"))

this calls the printButtonAndCoords function, and passes the
result to the bind function.

(well, to be precise, it gives a TypeError exception)

try this instead:

    Button1.bind("<Enter>", lambda e: printButtonAndCoords(e, "button1"))
    Button2.bind("<Enter>", lambda e: printButtonAndCoords(e, "button2"))

(the lambda statement creates a callable object taking one
argument, which it passes on to the printButtonAndCoords
function)

you might prefer writing this as

    callback = lambda e: printButtonAndCoords(e, "button1")
    Button1.bind("<Enter>", callback)
    callback = lambda e: printButtonAndCoords(e, "button2")
    Button2.bind("<Enter>", callback)

or even:

    def callback(e):
        printButtonAndCoords(e, "button1")
    Button1.bind("<Enter>", callback)

    def callback(e):
        printButtonAndCoords(e, "button2")
    Button2.bind("<Enter>", callback)

hope this helps!

</F>

<!-- (the eff-bot guide to) the python standard library:
http://www.pythonware.com/people/fredrik/librarybook.htm
-->





More information about the Python-list mailing list