Skip to content

Instantly share code, notes, and snippets.

@taleinat
Last active July 28, 2019 06:17
Show Gist options
  • Save taleinat/985f1d47ea73b133b2faed77bd88d928 to your computer and use it in GitHub Desktop.
Save taleinat/985f1d47ea73b133b2faed77bd88d928 to your computer and use it in GitHub Desktop.
Python Tkinter Scrollable Text
# Copyright 2019 Tal Einat
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
from functools import update_wrapper
from tkinter import Frame, Scrollbar, Text, NONE,\
HORIZONTAL, VERTICAL, EW, NS, NSEW, TclError
__all__ = ['AutoHiddenScrollbar', 'add_config_callback', 'ScrollableTextFrame']
class AutoHiddenScrollbar(Scrollbar):
"""A scrollbar that is automatically hidden when not needed.
Only the grid geometry manager is supported.
"""
def set(self, lo, hi):
if float(lo) > 0.0 or float(hi) < 1.0:
self.grid()
else:
self.grid_remove()
super().set(lo, hi)
def pack(self, **kwargs):
raise TclError(f'{self.__class__.__name__} does not support "pack"')
def place(self, **kwargs):
raise TclError(f'{self.__class__.__name__} does not support "place"')
def add_config_callback(config_callback):
"""Class decorator adding a configuration callback for Tk widgets.
The supplied callback will be called whenever a configuration change
is made to an instance of the decorated class, except if changes are
made directly at the Tk level, i.e. not via the Tkinter interface.
The callback will be called with a single dict parameter, containing
the new configuration info.
The callback is called before the configuration change is made to
the underlying widget, so that the previous configuration values may
be inspected by calling the widget's .configure() method.
"""
def decorator(cls):
class WidgetWithConfigHook(cls):
def __setitem__(self, key, value):
config_callback({key: value})
super().__setitem__(key, value)
def configure(self, cnf=None, **kw):
if cnf is not None:
config_callback(cnf)
if kw:
config_callback(kw)
super().configure(cnf=cnf, **kw)
config = configure
update_wrapper(WidgetWithConfigHook, cls, updated=[])
return WidgetWithConfigHook
return decorator
class ScrollableTextFrame(Frame):
"""Frame with a Text widget and scroll bars.
Scrollbars are dynamically shown and hidden according to the
contents of the text widget, so that they are shown only when
needed.
"""
def __init__(self, master, **kwargs):
"""Initialize the frame, scroll bars and text widget.
master - master widget for this frame
The Text widget is accessible via the 'text' attribute.
Its 'wrap' setting is initially set to 'none'; it can be
changed be calling e.g. `text.configure(wrap=tkinter.WORD)`.
"""
super().__init__(master, **kwargs)
@add_config_callback(self._handle_wrap)
class TextWithConfigHook(Text):
pass
self.text = TextWithConfigHook(self, wrap=NONE)
self.text.grid(row=0, column=0, sticky=NSEW)
self.grid_rowconfigure(0, weight=1)
self.grid_columnconfigure(0, weight=1)
# vertical scrollbar
self.yscroll = AutoHiddenScrollbar(self, orient=VERTICAL,
takefocus=False,
command=self.text.yview)
self.yscroll.grid(row=0, column=1, sticky=NS)
self.text['yscrollcommand'] = self.yscroll.set
# horizontal scrollbar
self.xscroll = AutoHiddenScrollbar(self, orient=HORIZONTAL,
takefocus=False,
command=self.text.xview)
self.xscroll.grid(row=1, column=0, sticky=EW)
self.text['xscrollcommand'] = self.xscroll.set
self.has_horiz_scroll = True
def _handle_wrap(self, cnf):
if 'wrap' in cnf:
self._set_xscroll(cnf['wrap'])
def _set_xscroll(self, wrap):
"""show/hide the horizontal scrollbar as per the 'wrap' setting"""
# show the scrollbar only when wrap is set to NONE
if wrap != NONE and self.has_horiz_scroll:
self.xscroll.grid_remove()
self.text['xscrollcommand'] = ''
self.has_horiz_scroll = False
elif wrap == NONE and not self.has_horiz_scroll:
self.xscroll.grid()
self.text['xscrollcommand'] = self.xscroll.set
self.has_horiz_scroll = True
# Copyright 2019 Tal Einat
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import unittest
from tkinter import Tk, CHAR, NONE, WORD
from scrollable_text import ScrollableTextFrame
class ScrollableTextFrameTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.root = root = Tk()
root.withdraw()
@classmethod
def tearDownClass(cls):
cls.root.update_idletasks()
cls.root.destroy()
del cls.root
def make_frame(self, **kwargs):
frame = ScrollableTextFrame(self.root, **kwargs)
def cleanup_frame():
frame.update_idletasks()
frame.destroy()
self.addCleanup(cleanup_frame)
return frame
def test_line1(self):
frame = self.make_frame()
text = frame.text
text.insert('1.0', 'lorem ipsum')
self.assertEqual(text.get('1.0', '1.end'), 'lorem ipsum')
def test_horiz_scrollbar(self):
# The horizontal scrollbar should be shown/hidden according to
# the 'wrap' setting: It should only be shown when 'wrap' is
# set to NONE.
frame = self.make_frame()
text = frame.text
# Check with default wrapping setting.
self.assertEqual(frame.has_horiz_scroll, text.cget('wrap') == NONE)
# Check after updating the 'wrap' setting in various ways.
text.config(wrap=NONE)
self.assertTrue(frame.has_horiz_scroll)
text.configure(wrap=CHAR)
self.assertFalse(frame.has_horiz_scroll)
text['wrap'] = NONE
self.assertTrue(frame.has_horiz_scroll)
text['wrap'] = WORD
self.assertFalse(frame.has_horiz_scroll)
if __name__ == '__main__':
unittest.main(verbosity=2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment