widget. Not entirely by coincidence, this brings us to the next point of interest on our
widget tour.
Text
It’s been said that tkinter’s strongest points may be its Text and Canvas widgets. Both
provide a remarkable amount of functionality. For instance, the tkinter Text widget
was powerful enough to implement the web pages of Grail, an experimental web
browser coded in Python; Text supports complex font-style settings, embedded images,
unlimited undo and redo, and much more. The tkinter Canvas widget, a general-purpose
drawing device, allows for efficient free-form graphics and has been the basis of so-
phisticated image-processing and visualization applications.
In Chapter 11, we’ll put these two widgets to use to implement text editors (PyEdit),
paint programs (PyDraw), clock GUIs (PyClock), and image programs (PyPhoto and
PyView). For the purposes of this tour chapter, though, let’s start out using these
widgets in simpler ways. Example 9-10 implements a simple scrolled-text display,
which knows how to fill its display with a text string or file.
Example 9-10. PP4E\Gui\Tour\scrolledtext.py
"a simple text or file viewer component"
print('PP4E scrolledtext')
from tkinter import *
class ScrolledText(Frame):
def init(self, parent=None, text='', file=None):
Frame.init(self, parent)
self.pack(expand=YES, fill=BOTH) # make me expandable
self.makewidgets()
self.settext(text, file)
def makewidgets(self):
sbar = Scrollbar(self)
text = Text(self, relief=SUNKEN)
sbar.config(command=text.yview) # xlink sbar and text
text.config(yscrollcommand=sbar.set) # move one moves other
sbar.pack(side=RIGHT, fill=Y) # pack first=clip last
text.pack(side=LEFT, expand=YES, fill=BOTH) # text clipped first
self.text = text
def settext(self, text='', file=None):
if file:
text = open(file, 'r').read()
self.text.delete('1.0', END) # delete current text
self.text.insert('1.0', text) # add at line 1, col 0
self.text.mark_set(INSERT, '1.0') # set insert cursor
self.text.focus() # save user a click
def gettext(self): # returns a string
528 | Chapter 9: A tkinter Tour, Part 2