is no reason that the text string cut couldn’t simply be stored in a Python instance
variable. But the clipboard is actually a much larger concept.
The clipboard used by this script is an interface to a system-wide storage space, shared
by all programs on your computer. Because of that, it can be used to transfer data
between applications, even ones that know nothing of tkinter. For instance, text cut or
copied in a Microsoft Word session can be pasted in a SimpleEditor window, and text
cut in SimpleEditor can be pasted in a Microsoft Notepad window (try it). By using the
clipboard for cut and paste, SimpleEditor automatically integrates with the window
system at large. Moreover, the clipboard is not just for the Text widget—it can also be
used to cut and paste graphical objects in the Canvas widget (discussed next).
As used in the script of Example 9-11, the basic tkinter clipboard interface looks like
this:
self.clipboard_clear() # clear the clipboard
self.clipboard_append(text) # store a text string on it
text = self.selection_get(selection='CLIPBOARD') # fetch contents, if any
All of these calls are available as methods inherited by all tkinter widget objects because
they are global in nature. The CLIPBOARD selection used by this script is available on all
platforms (a PRIMARY selection is also available, but it is only generally useful on X
Windows, so we’ll ignore it here). Notice that the clipboard selection_get call throws
a TclError exception if it fails; this script simply ignores it and abandons a paste request,
but we’ll do better later.
Composition versus inheritance
As coded, SimpleEditor uses inheritance to extend ScrolledText with extra buttons and
callback methods. As we’ve seen, it’s also reasonable to attach (embed) GUI objects
coded as components, such as ScrolledText. The attachment model is usually called
composition; some people find it simpler to understand and less prone to name clashes
than extension by inheritance.
To give you an idea of the differences between these two approaches, the following
sketches the sort of code you would write to attach ScrolledText to SimpleEditor with
changed lines in bold font (see the file simpleedit2.py in the book’s examples distribu-
tion for a complete composition implementation). It’s mostly a matter of passing in the
right parents and adding an extra st attribute name anytime you need to get to the
Text widget’s methods:
class SimpleEditor(Frame):
def __init__(self, parent=None, file=None):
Frame.__init__(self, parent)
self.pack()
frm = Frame(self)
frm.pack(fill=X)
Button(frm, text='Save', command=self.onSave).pack(side=LEFT)
...more...
Text | 537