Home > other >  Mouse binding of a tkinter canvas within a class isn't working
Mouse binding of a tkinter canvas within a class isn't working

Time:11-13

I am trying to make a button click draw something onto the canvas. Of course, the best way to do this is canvas.bind('<Button-1>', function), which is what I've done. I've even added a print statement to the function that it is supposed to call. But it's not doing anything! I run the app and click inside the canvas, but nothing is printed to the console. I've checked the bindings, tried different ones, tried bind_all, but nothing is working.

What am I doing wrong, and how do I fix it?

from time import sleep, process_time
import tkinter as tk

class App:
    def __init__(self):
        self.master = tk.Tk()
        self.master.title('Verlet Physics Playground')
        self.master.wm_attributes('-fullscreen', True)

        screenWidth = self.master.winfo_screenwidth()
        screenHeight = self.master.winfo_screenheight() - 50
        self.canvas = tk.Canvas(self.master, width=screenWidth, height=screenHeight, bg='white', highlightthickness=0)
        self.canvas.pack()

        self.drawMode = 'node'

        tk.Button(self.master, text='Node', command=self.nodeButton).pack(side='left')
        tk.Button(self.master, text='Constraint', command=self.constraintButton).pack(side='right')
        
        self.mouseDown, self.mouseX, self.mouseY = False, None, None
        self.canvas.bind('<Button-1>', self.mouseDown)
        self.canvas.bind('<B1-Motion>', self.mouseDrag)
        self.canvas.bind('<ButtonRelease-1>', self.mouseUp)

        self.master.mainloop()

    def nodeButton(self): self.drawMode = 'node'
    def constraintButton(self): self.drawMode = 'constraint'

    def mouseDown(self, event):
        print('test')
        self.mouseDown, self.mouseX, self.mouseY = True, event.x, event.y

    def mouseDrag(self, event):
        self.mouseX, self.mouseY = event.x, event.y

    def mouseUp(self, event):
        self.mouseDown, self.mouseX, self.mouseY = False, None, None

if __name__ == '__main__':
    App()

CodePudding user response:

You've bound the key to the function self.mouseDown but in another part of the code you redefine self.mouseDown to be a boolean rather than a function.

  • Related