Welcome, guest | Sign In | My Account | Store | Cart
# Version: 0.7
# Author: Miguel Martinez Lopez
# Uncomment the next line to see my email
# print ("Author's email: %s"% "61706c69636163696f6e616d656469646140676d61696c2e636f6d".decode("hex"))

import platform

OS = platform.system()

def build_mouse_wheel_handler(widget, orient, factor = 1):
    view_command = getattr(widget, orient+'view')
    
    if OS == 'Linux':
        def onMouseWheel(event):
            if event.num == 4:
                view_command("scroll",(-1)*factor,"units" )
            elif event.num == 5:
                view_command("scroll",factor,"units" ) 
            
    elif OS == 'Windows':
        def onMouseWheel(event):        
            view_command("scroll",(-1)*int((event.delta/120)*factor),"units" ) 
    
    elif OS == 'Darwin':
        def onMouseWheel(event):        
            view_command("scroll",event.delta,"units" )             
    
    return onMouseWheel

class ScrollingManager(object):    
    
    def __init__(self, root, horizontal_factor = 2, vertical_factor=2):
        
        self._active_area = None
        
        if isinstance(horizontal_factor, int):
            self.horizontal_factor = horizontal_factor
        else:
            raise Exception("Factor must be an integer.")

        if isinstance(vertical_factor, int):
            self.vertical_factor = vertical_factor
        else:
            raise Exception("Factor must be an integer.")

        if OS == "Linux" :
            root.bind_all('<4>', self._on_mouse_wheel,  add='+')
            root.bind_all('<5>', self._on_mouse_wheel,  add='+')
        else:
            # Windows and MacOS
            root.bind_all("<MouseWheel>", self._on_mouse_wheel,  add='+')

    def _on_mouse_wheel(self,event):
        if self._active_area:
            self._active_area.onMouseWheel(event)

    def _on_mouse_enter_scrolling_area(self, widget):
        self._active_area = widget

    def _on_mouse_leave_scrolling_area(self):
        self._active_area = None

    def add_scrolling(self, widget, xscrollbar=None, yscrollbar=None):
        if yscrollbar:
            widget.configure(yscrollcommand=yscrollbar.set)
            yscrollbar['command']=widget.yview

        if xscrollbar:
            widget.configure(xscrollcommand=xscrollbar.set)
            xscrollbar['command']=widget.xview
        
        widget.bind('<Enter>',lambda event: self._on_mouse_enter_scrolling_area(widget))
        widget.bind('<Leave>', lambda event: self._on_mouse_leave_scrolling_area())

        if xscrollbar and not hasattr(xscrollbar, 'onMouseWheel'):
            xscrollbar.onMouseWheel = build_mouse_wheel_handler(widget,'x', self.horizontal_factor)

        if yscrollbar and not hasattr(yscrollbar, 'onMouseWheel'):
            yscrollbar.onMouseWheel = build_mouse_wheel_handler(widget,'y', self.vertical_factor)

        main_scrollbar = yscrollbar if yscrollbar is not None else xscrollbar
        
        if main_scrollbar:
            widget.onMouseWheel = main_scrollbar.onMouseWheel

        for scrollbar in (xscrollbar, yscrollbar):
            if scrollbar:
                scrollbar.bind('<Enter>', lambda event, scrollbar=scrollbar: self._on_mouse_enter_scrolling_area(scrollbar) )
                scrollbar.bind('<Leave>', lambda event: self._on_mouse_leave_scrolling_area())

if __name__== '__main__':
    try:
        from Tkinter import Tk, Scrollbar, Text
        from Tkconstants import *
    except ImportError:
        from tkinter import Tk, Scrollbar, Text
        from tkinter.constants import *

    root = Tk()
    
    lorem_ipsum = """Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. """

    xscrollbar = Scrollbar(root, orient=HORIZONTAL)
    xscrollbar.pack(side=BOTTOM, fill=X)

    yscrollbar = Scrollbar(root)
    yscrollbar.pack(side=RIGHT, fill=Y)

    textarea = Text(root, wrap="none", height=20, width=27,
                xscrollcommand=xscrollbar.set,
                yscrollcommand=yscrollbar.set)
    textarea.pack()
    
    textarea.insert(1.0, "\n\n".join(lorem_ipsum.split(".")))

    scrolling_manater = ScrollingManager(root)
    scrolling_manater.add_scrolling(textarea, xscrollbar=xscrollbar, yscrollbar=yscrollbar)

    root.mainloop()

Diff to Previous Revision

--- revision 13 2017-04-07 19:50:28
+++ revision 14 2017-04-15 14:33:08
@@ -1,121 +1,119 @@
-# Version: 0.6
+# Version: 0.7
 # Author: Miguel Martinez Lopez
 # Uncomment the next line to see my email
 # print ("Author's email: %s"% "61706c69636163696f6e616d656469646140676d61696c2e636f6d".decode("hex"))
 
-
-import Tkinter as tk
-import ttk
-
 import platform
 
+OS = platform.system()
 
-class ScrollingArea(object):
-    OS = platform.system()
+def build_mouse_wheel_handler(widget, orient, factor = 1):
+    view_command = getattr(widget, orient+'view')
     
-    def __init__(self, root, factor = 2):
+    if OS == 'Linux':
+        def onMouseWheel(event):
+            if event.num == 4:
+                view_command("scroll",(-1)*factor,"units" )
+            elif event.num == 5:
+                view_command("scroll",factor,"units" ) 
+            
+    elif OS == 'Windows':
+        def onMouseWheel(event):        
+            view_command("scroll",(-1)*int((event.delta/120)*factor),"units" ) 
+    
+    elif OS == 'Darwin':
+        def onMouseWheel(event):        
+            view_command("scroll",event.delta,"units" )             
+    
+    return onMouseWheel
+
+class ScrollingManager(object):    
+    
+    def __init__(self, root, horizontal_factor = 2, vertical_factor=2):
         
-        self.activeArea = None
+        self._active_area = None
         
-        if type(factor) == int:
-            self.factor = factor
+        if isinstance(horizontal_factor, int):
+            self.horizontal_factor = horizontal_factor
         else:
             raise Exception("Factor must be an integer.")
 
-        if self.OS == "Linux" :
-            root.bind_all('<4>', self.onMouseWheel,  add='+')
-            root.bind_all('<5>', self.onMouseWheel,  add='+')
+        if isinstance(vertical_factor, int):
+            self.vertical_factor = vertical_factor
+        else:
+            raise Exception("Factor must be an integer.")
+
+        if OS == "Linux" :
+            root.bind_all('<4>', self._on_mouse_wheel,  add='+')
+            root.bind_all('<5>', self._on_mouse_wheel,  add='+')
         else:
             # Windows and MacOS
-            root.bind_all("<MouseWheel>", self.onMouseWheel,  add='+')
+            root.bind_all("<MouseWheel>", self._on_mouse_wheel,  add='+')
 
-    def onMouseWheel(self,event):
-        if self.activeArea:
-            self.activeArea.onMouseWheel(event)
+    def _on_mouse_wheel(self,event):
+        if self._active_area:
+            self._active_area.onMouseWheel(event)
 
-    def mouseWheel_bind(self, widget):
-        self.activeArea = widget
+    def _on_mouse_enter_scrolling_area(self, widget):
+        self._active_area = widget
 
-    def mouseWheel_unbind(self):
-        self.activeArea = None
+    def _on_mouse_leave_scrolling_area(self):
+        self._active_area = None
 
-    def build_function_onMouseWheel(self, widget, orient, factor = 1):
-        view_command = getattr(widget, orient+'view')
-        
-        if self.OS == 'Linux':
-            def onMouseWheel(event):
-                if event.num == 4:
-                    view_command("scroll",(-1)*factor,"units" )
-                elif event.num == 5:
-                    view_command("scroll",factor,"units" ) 
-                
-        elif self.OS == 'Windows':
-            def onMouseWheel(event):        
-                view_command("scroll",(-1)*int((event.delta/120)*factor),"units" ) 
-        
-        elif self.OS == 'Darwin':
-            def onMouseWheel(event):        
-                view_command("scroll",event.delta,"units" )             
-        
-        return onMouseWheel
-        
-
-    def add_scrolling(self, scrollingArea, xscrollbar=None, yscrollbar=None):
+    def add_scrolling(self, widget, xscrollbar=None, yscrollbar=None):
         if yscrollbar:
-            scrollingArea.configure(yscrollcommand=yscrollbar.set)
-            yscrollbar['command']=scrollingArea.yview
+            widget.configure(yscrollcommand=yscrollbar.set)
+            yscrollbar['command']=widget.yview
 
         if xscrollbar:
-            scrollingArea.configure(xscrollcommand=xscrollbar.set)
-            xscrollbar['command']=scrollingArea.xview
+            widget.configure(xscrollcommand=xscrollbar.set)
+            xscrollbar['command']=widget.xview
         
-        scrollingArea.bind('<Enter>',lambda event: self.mouseWheel_bind(scrollingArea))
-        scrollingArea.bind('<Leave>', lambda event: self.mouseWheel_unbind())
+        widget.bind('<Enter>',lambda event: self._on_mouse_enter_scrolling_area(widget))
+        widget.bind('<Leave>', lambda event: self._on_mouse_leave_scrolling_area())
 
         if xscrollbar and not hasattr(xscrollbar, 'onMouseWheel'):
-            xscrollbar.onMouseWheel = self.build_function_onMouseWheel(scrollingArea,'x', self.factor)
+            xscrollbar.onMouseWheel = build_mouse_wheel_handler(widget,'x', self.horizontal_factor)
 
         if yscrollbar and not hasattr(yscrollbar, 'onMouseWheel'):
-            yscrollbar.onMouseWheel = self.build_function_onMouseWheel(scrollingArea,'y', self.factor)
+            yscrollbar.onMouseWheel = build_mouse_wheel_handler(widget,'y', self.vertical_factor)
 
-        main_scrollbar = yscrollbar or xscrollbar
+        main_scrollbar = yscrollbar if yscrollbar is not None else xscrollbar
         
         if main_scrollbar:
-            scrollingArea.onMouseWheel = main_scrollbar.onMouseWheel
+            widget.onMouseWheel = main_scrollbar.onMouseWheel
 
         for scrollbar in (xscrollbar, yscrollbar):
             if scrollbar:
-                scrollbar.bind('<Enter>', lambda event, scrollbar=scrollbar: self.mouseWheel_bind(scrollbar) )
-                scrollbar.bind('<Leave>', lambda event: self.mouseWheel_unbind())
+                scrollbar.bind('<Enter>', lambda event, scrollbar=scrollbar: self._on_mouse_enter_scrolling_area(scrollbar) )
+                scrollbar.bind('<Leave>', lambda event: self._on_mouse_leave_scrolling_area())
 
 if __name__== '__main__':
-    root = tk.Tk()
+    try:
+        from Tkinter import Tk, Scrollbar, Text
+        from Tkconstants import *
+    except ImportError:
+        from tkinter import Tk, Scrollbar, Text
+        from tkinter.constants import *
 
-    xScrollbar = ttk.Scrollbar(root, orient=tk.HORIZONTAL)
-    xScrollbar.grid(row=1, column=0, sticky= "ew")
+    root = Tk()
+    
+    lorem_ipsum = """Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. """
 
-    yScrollbar = ttk.Scrollbar(root, orient=tk.VERTICAL)
-    yScrollbar.grid(row=0, column=1,sticky="ns")
+    xscrollbar = Scrollbar(root, orient=HORIZONTAL)
+    xscrollbar.pack(side=BOTTOM, fill=X)
 
-    canvas1 = tk.Canvas(root, width=300, height=100, highlightthickness=0)
+    yscrollbar = Scrollbar(root)
+    yscrollbar.pack(side=RIGHT, fill=Y)
+
+    textarea = Text(root, wrap="none", height=20, width=27,
+                xscrollcommand=xscrollbar.set,
+                yscrollcommand=yscrollbar.set)
+    textarea.pack()
     
-    canvas1.grid(row=0, column=0)
-    
-    frameWindows= tk.Frame(canvas1)
-    frameWindows.pack()
+    textarea.insert(1.0, "\n\n".join(lorem_ipsum.split(".")))
 
-    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())
-    
-    ScrollingArea(root).add_scrolling(canvas1, xscrollbar=xScrollbar, yscrollbar=yScrollbar)
+    scrolling_manater = ScrollingManager(root)
+    scrolling_manater.add_scrolling(textarea, xscrollbar=xscrollbar, yscrollbar=yscrollbar)
 
     root.mainloop()

History