Mouse Events

Capturing mouse events inside our tkinter program.

Moving #

We can bind to mouse movement by using widget.bind("<Motion>", motion_handler). This is a very noisy (registers on every pixel moved) and imprecise (but not quite every pixel) event so we cannot recommend it for general use. This will register the correct position once the mouse settles. For a better solution reference the dragging section below.

Clicking #

There's multiple ways to bind to a mouse click event:

All of these options can be suffixed with -{num} where num is a single digit. 1=left click, 2=right click & 3=middle click (scroll wheel click). An alternative to this is using the .num attribute on the event object.

import tkinter

root = tkinter.Tk()

def click_handler(event):
# event also has x & y attributes
if event.num == 2:
        print("RIGHT CLICK")

root.bind("<Button-1>", lambda x: print("LEFT CLICK"))
root.bind("<Button>", click_handler)


Dragging #

To capture a click-and-drag event use any of the <B1-Motion> (left-click), <B2-Motion> (right click) or <B3-Motion> (middle mouse button click). Note that Note that when dragging outside of an element the event still fires.

# Dragging
import tkinter

root = tkinter.Tk()
label = tkinter.Label(root, text="HEY")

def drag_handler(event):
    print(event.x, event.y)

label.bind("<B1-Motion>", drag_handler)


Hovering #

Hovering over an element sends out two events in sequence: <Enter> and <Leave>

import tkinter

root = tkinter.Tk()

label = tkinter.Label(root, text="HELLO", bg="white", fg="navy")
label.bind("<Enter>", lambda event: event.widget.config(bg="navy", fg="white"))
label.bind("<Leave>", lambda event: event.widget.config(bg="white", fg="navy"))


Hovering the text shows it with a blue background and leaving it sets it back to default.

entering the label leaving the label