1

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 Answers2

1

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.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
  • @WojtekSmelcerz I absolutely guarantee it’s the correct event to bind to. This isn’t an opinion, it’s a fact. If it’s not working, you’re doing something wrong. Without seeing what you did, it’s impossible for me to guess. – Bryan Oakley Jun 28 '23 at 19:49
  • @WojtekSmelcerz If you’re wanting to do something while the button is pressed _and moving_ you can use `` – Bryan Oakley Jun 28 '23 at 19:51
  • It works now, thanks! – Wojtek Smelcerz Jun 29 '23 at 14:55
1

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))
JRiggles
  • 4,847
  • 1
  • 12
  • 27