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?
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 )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.