Attaching event to self (canvas) tkinter

 ̄綄美尐妖づ 提交于 2021-01-29 08:06:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!