Using the Mouse Wheel with Tkinter (Python)


This short Python snippet shows you how to read mouse wheel events with the Tkinter GUI toolkit. Windows and Linux have different bindings and read different events, but can be included in the same program code for use with either operating system.

# explore the mouse wheel with the Tkinter GUI toolkit
# Windows and Linux generate different events
# tested with Python25

import Tkinter as tk

def mouse_wheel(event):
    global count
    # respond to Linux or Windows wheel event
    if event.num == 5 or == -120:
        count -= 1
    if event.num == 4 or == 120:
        count += 1
    label['text'] = count

count = 0
root = tk.Tk()
root.title('turn mouse wheel')
root['bg'] = 'darkgreen'

# with Windows OS
root.bind("<MouseWheel>", mouse_wheel)
# with Linux OS
root.bind("<Button-4>", mouse_wheel)
root.bind("<Button-5>", mouse_wheel)

label = tk.Label(root, font=('courier', 18, 'bold'), width=10)
label.pack(padx=40, pady=40)

Isn't it about time forums rewarded their contributors?

Earn rewards points for helping others. Gain kudos. Cash out. Get better answers yourself.

It's as simple as contributing editorial or replying to discussions labeled or OP Kudos

This is an OP Kudos discussion and contributors may be rewarded
Start New Discussion
Tags Related to this Article