问题
i have created a class in python that extends the tkinter canvas. I am trying to attach an event to this canvas to handle click's within the class. It functions if i attach the event outside of the class itself but when binding within the class the click event only occur's once and then proceeds not to do anything at all only performing the first click:
class myCanvas(Canvas):
def callback(event):
print('clicked at', event.x, event.y)
def __init__(self, parent, **kwargs):
Canvas.__init__(self, parent, **kwargs)
self.bind("<Button-1>", self.callback())
self.height = self.winfo_reqheight()
self.width = self.winfo_reqwidth()
Binding the event functions correctly only if i attach the event outside of the class. Any help in finding a way to attach the event to the extended canvas would be appreciated.
回答1:
The problem is in this line:
self.bind("<Button-1>", self.callback())
You need to connect something callable (in other words, a function) to the event. The function is referenced as self.callback
. If you call the function (self.callback()
) then you're connecting the return value of self.callback()
to the click event instead of the function itself.
来源:https://stackoverflow.com/questions/38619393/attaching-event-to-self-canvas-tkinter