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 Grail web browser, discussed in Chapter 15; it supports complex font style settings, embedded images, and much more. The Tkinter Canvas widget, a general-purpose drawing device, has also been the basis of sophisticated image processing and visualization applications.

In Chapter 9, we’ll put these two widgets to use to implement text editors (PyEdit), paint programs (PyDraw), clock GUIs (PyClock), and photo slideshows (PyView). For the purposes of this tour chapter, though, let’s start out using these widgets in simpler ways. Example 8-10 implements a simple scrolled-text display, which knows how to fill its display with a text string or file.

Example 8-10. PP2E\Gui\Tour\scrolledtext.py

# a simple text or file viewer component print 'PP2E 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 ...

Get Programming Python, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.