To bind a Tkinter event to the left mouse button being held down, we can take the following steps −
Create an instance of tkinter frame.
Set the size of the frame using win.geometry method.
Define an event handler "handler1" to print a statement when the mouse is moved with the left button being held down.
Define another event handler "handler2" to print a statement when the mouse button is released.
Use the bind method to bind <B1-Motion> with handler1.
Use the bind method again to bind <ButtonRelease-1> with hander2.
Finally, run the mainloop of the application window.
Example
# Import required libraries from tkinter import * # Create an instance of tkinter frame win = Tk() # Define the geometry of the window win.geometry("750x250") # Define a function def handler1(e): print("You are moving the Mouse with the Left Button Pressed.") def handler2(e): print("Button Released") # Define a Label in Main window Label(win, text="Move the Mouse with the Left Button Pressed", font='Helvetica 15 underline').pack(pady=30) # Bind the Mouse events with the Handler win.bind('<B1-Motion>', handler1) win.bind('<ButtonRelease-1>', handler2) win.mainloop()
Output
When you execute the code, it will show the following screen −
Now, move the mouse with the Left Button pressed and it will show the following output on the console
You are moving the Mouse with the Left Button Pressed. You are moving the Mouse with the Left Button Pressed. You are moving the Mouse with the Left Button Pressed. You are moving the Mouse with the Left Button Pressed. You are moving the Mouse with the Left Button Pressed.
When you release the Left Button of the mouse, it will show the following −
Button Released