Luke__
Luke__

Reputation: 247

Can tkinter handle mouse wheel forward and backward events separately?

I'm tring to program a simple zoom in and zoom out program using a canvas on tkinter, I've done most of the work, but I was stopped by an issue: when binding the event using master.bind(<Control-MouseWheel>, func) I can't handle differently the mouse wheel forward event and backward event. Is there any solution?

P.S. When binding an event, I was forced to use master.bind(<Control-MouseWheel>, lambda func: "other code"), otherwise when the program ran, the event-binded function was instantaneously executed, any solution for this other problem?

Upvotes: 1

Views: 942

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 386382

The event object has an attribute named delta which tells you how many units to move. The delta can be positive (move forward) or negative (move backwards).

def func(event):
    if event.delta > 0:
        print("scroll forward")
    else:
        print("scroll backward")

From the canonical documentation:

The delta value represents the rotation units the mouse wheel has been moved. On Windows 95 & 98 systems the smallest value for the delta is 120. Future systems may support higher resolution values for the delta. The sign of the value represents the direction the mouse wheel was scrolled.

On windows and *nix systems you typically need to divide delta by 120 (or some other value, depending on how fast you want to zoom) if you want to use the value to determine how much to scroll or zoom. On OSX you can use the raw delta values.

For a complete example of zooming with the mouse wheel, see this answer to the question Tkinter canvas zoom + move/pan

Upvotes: 3

Related Questions