0

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.

D3181
  • 2,037
  • 5
  • 19
  • 44
  • 1
    Cannot reproduce, works perfectly fine. ("Perfectly fine" meaning it shows an error every time I click because it's missing the `self` parameter.) Not sure if it matters, but what python version are you using? – Aran-Fey Jul 27 '16 at 17:20
  • Really? I'm using python 3.5 and Pycharm and it runs for me but I just doesn't work as I expect – D3181 Jul 27 '16 at 17:27
  • Do you mean the class header class mycanvas () is missing the self parameter? – D3181 Jul 27 '16 at 17:28
  • No, the callback expects a `self`. – Aran-Fey Jul 27 '16 at 17:30
  • 1
    __Don't__ call the callback when connecting it. That should be `self.bind("", self.callback)` __without__ parentheses after `callback`. – Aran-Fey Jul 27 '16 at 17:34
  • ok made the amendments and it works now! thanks for the advice, if you post it as an answer i'll accept it :) – D3181 Jul 27 '16 at 17:36

1 Answers1

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.

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149