# Version: 0.1 # Author: Miguel Martinez Lopez # Uncomment the next line to see my email # print "Author's email: ", "61706c69636163696f6e616d656469646140676d61696c2e636f6d".decode("hex") import Tkinter as tk import ttk class MouseWheel(object): def __init__(self, root, factor = 0.5): self.activeWidget = None self.factor = factor import platform os = platform.system() if os == "Linux" : root.bind_all('<4>', self.onMouseWheel, add='+') root.bind_all('<5>', self.onMouseWheel, add='+') else: # Windows and MacOS root.bind_all("<MouseWheel>", self.onMouseWheel, add='+') def onMouseWheel(self,event): print self.orient if self.activeWidget: if self.orient == tk.HORIZONTAL: self.activeWidget.xview("scroll",(-1)*int(event.delta/(120*self.factor)),"units" ) elif self.orient == tk.VERTICAL: self.activeWidget.yview("scroll", (-1)*int(event.delta/(120*self.factor)),"units" ) else: if self.activeWidget['yscrollcommand']: self.activeWidget.yview("scroll", (-1)*int(event.delta/(120*self.factor)),"units" ) elif self.activeWidget['xscrollcommand']: self.activeWidget.xview("scroll",(-1)*int(event.delta/(120*self.factor)),"units" ) def mouseWheel_bind(self, widget, orient = None): self.activeWidget = widget self.orient = orient def mouseWheel_unbind(self, widget): self.activeWidget = None self.orient = None def add_scrolling(self, area, xscrollbar=None, yscrollbar=None): area.bind('<Enter>',lambda event: self.mouseWheel_bind(area)) area.bind('<Leave>', lambda event: self.mouseWheel_unbind(area)) for scrollbar in (xscrollbar, yscrollbar): if scrollbar: scrollbar.bind('<Enter>', lambda event, orient=str(scrollbar['orient']): self.mouseWheel_bind(area, orient) ) scrollbar.bind('<Leave>', lambda event: self.mouseWheel_unbind(area)) def test(): root = tk.Tk() xScrollbar = ttk.Scrollbar(root, orient=tk.HORIZONTAL) xScrollbar.grid(row=1, column=0, sticky= "ew") yScrollbar = ttk.Scrollbar(root, orient=tk.VERTICAL) yScrollbar.grid(row=0, column=1,sticky="ns") canvas1 = tk.Canvas(root, width=300, height=100,xscrollcommand=xScrollbar.set, yscrollcommand=yScrollbar.set) canvas1.grid(row=0, column=0) frameWindows= tk.Frame(canvas1) frameWindows.pack() for i in range(20): rowFrame = tk.Frame(frameWindows) rowFrame.pack() for j in range(8): tk.Label(rowFrame, text="Label %s, %s" % (str(i), str(j))).pack(side=tk.LEFT) canvas1.create_window(0, 0, window=frameWindows, anchor='nw') canvas1.update_idletasks() canvas1['scrollregion'] = (0,0,frameWindows.winfo_reqwidth(), frameWindows.winfo_reqheight()) yScrollbar['command']=canvas1.yview xScrollbar['command']=canvas1.xview MouseWheel(root).add_scrolling(canvas1,xscrollbar=xScrollbar, yscrollbar=yScrollbar) root.mainloop() if __name__== '__main__': test()