[Tkinter-discuss] Tkinter Canvas MouseWheel problem.

Martin B. spooky.ln at tbs-software.com
Sun Mar 27 12:43:06 CEST 2011


hi all,
maybe this is stupid question but i cannot catch mousewheel event in 
Tk.Canvas.
I tryied <MouseWheel>, <Button-4>, <4> but without any luck. <1>, <2>, 
<3> working.
I'm on Win7 Python3.2.
here is my example. Is something wrong in code or i need some magic to 
catch this event.
thanks.

#encoding: utf-8
from tkinter import *
import tkinter.ttk as ttk
from PIL import Image, ImageTk

class PhotoView(Canvas):
     def __init__(self, parent, **kw):
         self.frame = Frame(parent, bd=2, relief='sunken')
         self.frame.rowconfigure(0, weight=1)
         self.frame.columnconfigure(0, weight=1)

         super().__init__(self.frame)
         Canvas.grid(self, column=0, row=0, sticky='news')

         xscroll = ttk.Scrollbar(self.frame, orient=HORIZONTAL)
         xscroll.grid(column=0, row=1, sticky='we')
         yscroll = ttk.Scrollbar(self.frame, orient=VERTICAL)
         yscroll.grid(column=1, row=0, sticky='sn')

         self.config(width=640,
                     height=480,
                     xscrollcommand=xscroll.set,
                     yscrollcommand=yscroll.set)

         xscroll.config(command=self.xview)
         yscroll.config(command=self.yview)

         # reset coordinate system
         self.xview_moveto(0)
         self.yview_moveto(0)

         # binding
         self.bind('<Configure>', self.make_scroll)
         self.bind('<B3-Motion>', self.drag_image)
         self.bind('<Button-4>', self.zoom_image) # dont work
         self.bind('<MouseWheel>', self.zoom_image) # dont work

         self.focus()

     def drag_image(self, event=None):
         pass

     def make_scroll(self, event=None):
         self.config(scrollregion=self.bbox(ALL))

     def zoom_image(self, event=None):
         print(event)

     def grid(self, **kw):
         self.frame.grid(**kw)

     def pack(self, **kw):
         self.frame.pack(**kw)


class mainGui(Tk):
     def __init__(self):
         super().__init__()

         im = ImageTk.PhotoImage(Image.open('test_img.jpg'))

         c = PhotoView(self)
         c.pack(fill='both', expand='yes')
         c.create_image(0, 0, image=im, anchor='nw')
         c.image = im # keep reference !!

if __name__ == '__main__':
     app = mainGui()
     app.mainloop()



More information about the Tkinter-discuss mailing list