Chris Aung Chris Aung - 1 year ago 307
Python Question

Python tkinter binding mousewheel to scrollbar

I have this scroll-able frame (frame inside canvas actually).

import Tkinter as tk
class Scrollbarframe():
def __init__(self, parent,xsize,ysize,xcod,ycod):
def ScrollAll(event):

I would like to bind mouse wheel to the scrollbar so that user can scroll down the frame without having to use arrow buttons on the scrollbar. After looking around, i added a binding to my
like this

self.frame1.bind("<MouseWheel>", self.OnMouseWheel)

This is the function:

def OnMouseWheel(self,event):
return "break"

But the scroll bar won't move when i use mousewheel. Can anyone help me with this? All i want is when the user use mousewheel (inside the frame area/on the scrollbar), the canvas should automatically scroll up or down.

Answer Source

Perhaps the simplest solution is to make a global binding for the mousewheel. It will then fire no matter what widget is under the mouse or which widget has the keyboard focus. You can then unconditionally scroll the canvas, or you can be smart and figure out which of your windows should scroll.

For example, on windows you would do something like this:

self.canvas = Canvas(...)
self.canvas.bind_all("<MouseWheel>", self._on_mousewheel)
def _on_mousewheel(self, event):
    self.canvas.yview_scroll(-1*(, "units")

Note that self.canvas.bind_all is a bit misleading -- you more correctly should call root.bind_all but I don't know what or how you define your root window. Regardless, the two calls are synonymous.

Platform differences:

  • On Windows, you bind to <MouseWheel> and you need to divide by 120 (or some other factor depending on how fast you want the scroll)
  • on OSX, you bind to <MouseWheel> and you need to use without modification
  • on X11 systems you need to bind to <Button-4> and <Button-5>, and you need to divide by 120 (or some other factor depending on how fast you want to scroll)

There are more refined solutions involving virtual events and determining which window has the focus or is under the mouse, or passing the canvas window reference through the binding, but hopefully this will get you started.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download