How do i bind "mouse is pressed" in Python's tkinter?

137 Views Asked by At

I'm new to tkinter and I'm coding a simple "Paint" program, that draws a pixel on screen when I press my mouse.

So i tried to bind my function "is_pressed" like this:

#is pressed
def is_pressed(event):
    print('Mouse is pressed!')

#creating canvas
my_canvas = tkinter.Canvas(height=400, width=600)
my_canvas.pack()

#binding
my_canvas.bind('<Button-1>', is_pressed)

Now, I want this function to run when mouse is pressed, not when it's just clicked. How do i do it?

2

There are 2 best solutions below

1
JRiggles On BEST ANSWER

For something like 'painting' with the mouse, I've usually used bind('<B1-Motion>', <callback>)

Naturally, you can bind this to other buttons using B2 or B3 instead.

The caveat here is that the event doesn't trigger immediately - you have to move the mouse first. You could easily bind a second handler to <'Button-1'> though

# this should catch the moment the mouse is pressed as well as any motion while the
# button is held; the lambdas are just examples - use whatever callback you want
my_canvas.bind('<ButtonPress-1>', lambda e: print(e))
my_canvas.bind('<B1-Motion>', lambda e: print(e))
2
Bryan Oakley On

The event you need to bind to is <ButtonPress-1>, if you want to call a function when the button is pressed.

If you want to continuously call a function when the mouse is moved while the button is pressed, then you can bind to <B1-Motion>. That would allow you to draw as the user moves the mouse around.