1

I have two canvases (elements):

self.canvas1
self.canvas2

I want them to do something() when the mouse hover over the canvas.

So I hook it up using the bind('<Enter>'):

self.canvas1.bind('<Enter>', something)
self.canvas2.bind('<Enter>', something)

In the something() it will try to configure the canvas to red background color so:

def something(event):
    canvas.configure(background='red')

The tricky part is, how does the function something know which canvas it suppose to change its background color to?

Programer Beginner
  • 1,377
  • 6
  • 21
  • 47

1 Answers1

4

The event object has a widget attribute, which refers to the widget that generated the event. You could use that.

event.widget.configure(background="red")

If, for whatever reason, you don't want to do this, you could create an anonymous function which keeps a closure of your widget variable, and then you can pass it as an argument to your function directly.

self.canvas1.bind('<Enter>', lambda event: something(self.canvas1))
#or possibly*
self.canvas1.bind('<Enter>', lambda event, canvas1=self.canvas1: something(canvas1))

You'd have to change your something function's parameters to def something(widget): in that case.

(*The canvas1=self.canvas1 is only necessary if you're binding in a loop, as in Tkinter assign button command in loop with lambda)

Kevin
  • 74,910
  • 12
  • 133
  • 166
  • The first solution `event.widget.configure(background="red")` is much better and is perfect for me. I just had to wait for the _accept answer cool down_ – Programer Beginner Oct 22 '18 at 15:01