Syntax:
widget.bind(event, handler)
widget: The Tkinter widget you want to bind the event to.
event: A string that specifies the type of event (e.g., <Button-1> for a left mouse click).
KeyPress, Button-1, Button-2, Button-3, Motion...
handler: The callback function that will be executed when the event occurs.
-----------------------------------------------------------------------------------------------------------------
event.keysym: The key symbol (e.g., 'a', 'Enter').
event.x and event.y: The x and y coordinates of the mouse event.
event.widget: The widget that triggered the event.
-----------------------------------------------------------------------------------------------------------------
import tkinter as tk
def on_key_press(event):
print(f"key pressed: {event.keysym}")
def on_left_click(event):
print(f"left click at: ({event.x},{event.y})")
def on_right_click(event):
print(f"right click at: ({event.x},{event.y})")
def on_moude_motion(event):
print(f"mouse moved to: ({event.x},{event.y})")
root = tk.Tk()
root.title("Event handling example")
root.bind("<KeyPress>", on_key_press)
root.bind("<Button-1>",on_left_click)
root.bind("<Button-3>",on_right_click)
root.bind("<Motion>",on_moude_motion)
root.mainloop()