pythontkintermouseclick-event

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


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?


Solution

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