Interactive Events in Tkinter: Handling User Inputs and Actions
<Button-1>
Mouse Left button click
<Button-2>
Mouse center button click
<Button-3>
Mouse Right button click
<B1-Motion>
Mouse Left button Press and move
<ButtonRelease-1>
Mouse Left button release, ButtonRelease-2 for Middle and 3 for right button.
<Double-Button-1>
Left Mouse key is double clicked.
<Enter>
Mouse Entry over a widget
<Leave>
Mouse Leave a widget
<MouseWheel>
Mouse Wheel Up or Down rotation
Tkinter binding Mouse button wheel and movement events capturing and triggering callback functions
event.x event.y
Based on any event we can read the x, y coordinates of the position by reading event.x and event.y values. Here is a function which displays the x and y coordinates inside a Label. We used config() to update the text option of the Label.
def my_callback(event):
l1.config(text='Clicked at : '+ str(event.x) +","+ str(event.y))
Bind Events
We can bind various mouse events of parent window ( or any widget ) and trigger the callback function.
Here is a sample of using left mouse button click to call my_callback() function.
my_w.bind('<Button-1>',my_callback) #Mouse Left button click
import tkinter as tk # Python 3
my_w = tk.Tk()
my_w.geometry("615x400")
def my_callback(event):
l1.config(text='Clicked the key : '+ event.char)
l1=tk.Label(my_w,text='to Display',bg='yellow',font=('Times',26,'normal'))
l1.grid(row=0,column=1,padx=10,pady=10)
my_w.bind('<a>',my_callback) # Key a is pressed
my_w.bind('<K>',my_callback) # Key K is pressed
my_w.mainloop()
Difference between KeyPress and KeyRelease
Here the function my_t1() change the background colour of Entry widget t1 once the number of char exceeds 5. Here the KeyPress event will react after 7 chars are entered. However KeyRelease event will trigger the change in background colour once 6th char is entered.
Difference between KeyPress and KeyRelease events.→
This Tkinter application demonstrates how to use a keyboard shortcut (Ctrl+1) to open a new window.
import tkinter as tk
# Function to open a new Tkinter window
def open_window(event=None):
new_window = tk.Toplevel(root)
new_window.title("New Window")
new_window.geometry("300x200")
label = tk.Label(new_window, text="This is a new window!", font=("Arial", 14), fg="#dc3545")
label.pack(pady=20)
# Main Tkinter window
root = tk.Tk()
root.title("Shortcut Key Example")
root.geometry("400x300")
# Label for instructions with Bootstrap 'text-primary' color
instructions = tk.Label(root, text="Press Ctrl+1 to open a new window", font=("Arial", 12), fg="#007bff")
instructions.pack(pady=50)
# Bind Ctrl+1 to the open_window function
root.bind("<Control-Key-1>", open_window)
# Run the Tkinter event loop
root.mainloop()