draggable Tkinter.Text widget

infidel saint.infidel at gmail.com
Fri Aug 3 15:18:42 EDT 2007


Inspired by effbot's recent Vroom! editor, I have been toying with my
own version.  I'd like to make the Text widget "draggable", kind of
like how you can drag a PDF document up and down in Adobe Reader.

Here's what I have so far:

from Tkinter import *

class Draggable(Text, object):

    def __init__(self, parent, **options):
        Text.__init__(self, parent, **options)
        self.config(
            borderwidth=0,
            font="{Lucida Console} 10",
            foreground="green",
            background="black",
            insertbackground="white", # cursor
            selectforeground="green", # selection
            selectbackground="#008000",
            wrap=WORD, # use word wrapping
            undo=True,
            width=80,
        )
        self.bind('<Button-3>', self.handle_mousedown3)
        self.bind('<B3-Motion>', self.handle_drag3)

    def handle_mousedown3(self, event=None):
        self._y = event.y

    def handle_drag3(self, event=None):
        self.yview_scroll(self._y - event.y, UNITS)
        self._y = event.y

if __name__ == '__main__':
    root = Tk()
    root.protocol("WM_DELETE_WINDOW", root.quit)
    root.config(background='black')
    root.wm_state("zoomed")
    text = Draggable(root)
    text.delete(1.0, END)
    text.insert(END, '\n'.join(str(x) for x in xrange(1, 1001)))
    text.pack(fill=Y, expand=True)
    root.mainloop()

This works fine, but because the mouse movements are in pixels and
scroll actions are in lines, the 'magnitude' of the scrolling is much
larger than the mouse movements causing them.  This isn't all bad, it
makes scanning a long document quickly easier, but I was wondering if
there was a simple way to add some "friction" to the scrolling so a
tiny mouse movement doesn't cause the text to go zipping by in a
flash.

Thanks,
infidel




More information about the Python-list mailing list