Mouse Events

Capturing mouse events inside our tkinter program.


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 refer to the “dragging” section below.


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)



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.

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 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