[Tkinter-discuss] Mouse wheel event for Canvas

Michael Lange klappnase at web.de
Fri Jun 23 23:46:19 CEST 2006


On Thu, 22 Jun 2006 14:24:46 +1000
John McMonagle <jmcmonagle at velseis.com.au> wrote:

> I tried binding mouse wheel events (<Button-4>, <Button-5>) to a Tkinter
> Canvas widget with the hope of using the event.delta value to
> subsequently scroll the Canvas.
> 
> However, it seems that event.delta always returns 0.
> 
> For example,
> 
> from Tkinter import *
> 
> r = Tk()
> c = Canvas(r, scrollregion=(0,0,500,500), height=200, width=200)
> s = Scrollbar(r, command=c.yview)
> c.pack(side=LEFT)
> s.pack(side=RIGHT, fill=Y)
> c.configure(yscrollcommand=s.set)
> c.create_rectangle(10,10,100,100)
> c.create_rectangle(10,200,100,300)
> 
> def rollWheel(event):
>     print event.delta
> 
> c.bind('<Button-4>', rollWheel)
> c.bind('<Button-5>', rollWheel)
> 
> c.focus_set()
> 
> r.mainloop()
> 
> 
> Has anyone successfully managed to wheel scroll a Tkinter Canvas
> widget ?
> 
Hi John,

here is a code snippet I have successfully used:

        self.canvas.bind('<4>', lambda event : self.canvas.xview('scroll', -1, 'units'))
        self.canvas.bind('<5>', lambda event : self.canvas.xview('scroll', 1, 'units'))

or if you do not like the lambda, you can use a callback like this:

    def rollWheel(event):
        if event.num == 4:
            self.canvas.xview('scroll', -1, 'units')
        elif event.num == 5:
            self.canvas.xview('scroll', 1, 'units')

I hope this helps

Michael


More information about the Tkinter-discuss mailing list