-1

I have been trying to bind a canvas to mouse click as described in this answer but within a class. The callback function is not getting invoked though. All related questions here seem to be calling the callback() function while trying to bind, rather than referencing it. I am referencing it, but it still doesn't work.

from tkinter import *

class BindingTrial():
    def __init__(self,root,canvas):
        self.root = root
        self.canvas = canvas
        self.canvas.bind("Button-1",self.callback)

    def callback(self,event):
        print ("clicked at", event.x, event.y)

root = Tk()
canvas= Canvas(root, width=100, height=100)
bt = BindingTrial(root,canvas)
canvas.pack()
root.mainloop()

0

1 Answer 1

2

You need to call the button bind with "<Button-1>", and the callback should accept self as the first parameter.

class BindingTrial():
    def __init__(self,root,canvas):
        self.root = root
        self.canvas = canvas
        self.canvas.bind('<Button-1>',self.callback)

    def callback(self, event):
        print ("clicked at", event.x, event.y)  
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.