Tk MouseWheel Support

MRAB python at mrabarnett.plus.com
Thu Mar 10 15:51:15 EST 2011


On 10/03/2011 20:28, Richard Holmes wrote:
> I am trying to use the mouse wheel to scroll a list box, but I'm not
> getting the event. When I bind "<Button-1>" to the listbox I get the
> event and I'm able to scroll using yview_scroll. I've tried binding
> "MouseWheel" and"<MouseWheel>", and I've also tried"<Button-4>" and
> "<Button-5>" even though I'm using Windows (XP, if that makes a
> difference). None of these works (I'm using print to see if I got to
> an event handler, and there's no printout).
>
> TIA for any help!
>
> Dick
>
Google found this:

     Using the Mouse Wheel with Tkinter (Python)
     http://www.daniweb.com/software-development/python/code/217059

which I adapted to get this (tested on XP with Python 2.7):

import Tkinter as tk

def mouse_wheel(event):
     dir = 0
     # respond to Linux or Windows wheel event
     if event.num == 5 or event.delta == -120:
         dir = 1
     if event.num == 4 or event.delta == 120:
         dir = -1
     listbox.yview_scroll(dir, "units")

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)

listbox = tk.Listbox(root)
listbox.pack()
for i in range(100):
     listbox.insert(tk.END, str(i))

root.mainloop()



More information about the Python-list mailing list