I'm new to tkinter and I'm writing a simple "paint" program. It's supposed to paint the canvas when the user presses their mouse.
I tried to bind the function like this:
def on_mouse_pressed(event):
"""On mouse pressed."""
print("Mouse is being pressed!")
my_canvas = tk.Canvas(root, width=960, height=540)
my_canvas.pack()
my_canvas.bind('<Button-1>', on_mouse_pressed)
It's important to run this function when the mouse is being pressed, not when it's just clicked. How can I bind it correctly?
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))