2

I was wondering if there is any way to get around using global variables in the callback functions that are used in bind in tkinter.

What I refer to is:

canvas = Canvas(root, width=500, height=500)
canvas.bind('<B1-Motion>', func)

where func is now some function that is triggered when the mouse is dragged. What I want is something like:

canvas.bind('<B1-Motion>', func(arg))

In combination with:

def func(event, arg):
    commands

I can see from https://docs.python.org/3/library/tkinter.html that one argument, which is the event itself, is given to the callback function, but it seems like waste of potential to not give this method any way to modify its callback in a different way.

Maybe I am mistaken and there is some technical reason why that is impossible in general or maybe there is an alternative to bind.

I was basically expecting something like:

buttoname = Button(...,...,..., command =  Lambda: func(arg))

If anyone has any pointers, it would be much appreciated.

regards

1 Answers1

1

Use a lambda that receives the event parameter and passes it along.

canvas.bind('<B1-Motion>', lambda e: func(e, arg))
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • What I don't get is, this looks like the function is evaluated in this line with the argument arg. But using it results in the function being evaluated with arg and whatever event has to offer, like in this case x and y. Is the function called twice? Is lambda effectively a wrapper? – Jannis Erhard Dec 28 '21 at 17:34
  • @JannisErhard: see https://stackoverflow.com/a/59687539/7432 for a brief description of how lambda works. – Bryan Oakley Dec 28 '21 at 17:41
  • The whole point of `lambda` is that it just defines an anonymous function, it doesn't call it. The function is called when the event occurs. @JannisErhard – Barmar Dec 28 '21 at 17:50
  • @JannisErhard for [a more detailed answer](https://stackoverflow.com/a/62742314/13629335) – Thingamabobs Dec 28 '21 at 18:23