-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()

REVOLUTION
  • 130
  • 2
  • 12

1 Answers1

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)  
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
stevers
  • 36
  • 1