[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1
Quitter(frm).pack(side=LEFT)
self.st = ScrolledText(self, file=file) # attach, not subclass
self.st.text.config(font=('courier', 9, 'normal'))

def onSave(self):
filename = asksaveasfilename()
if filename:
alltext = self.st.gettext() # go through attribute
open(filename, 'w').write(alltext)

def onCut(self):
text = self.st.text.get(SEL_FIRST, SEL_LAST)
self.st.text.delete(SEL_FIRST, SEL_LAST)
...more...

This code doesn’t need to subclass Frame necessarily (it could add widgets to the passed-
in parent directly), but being a frame allows the full package here to be embedded and
configured as well. The window looks identical when such code is run. I’ll let you be
the judge of whether composition or inheritance is better here. If you code your Python
GUI classes right, they will work under either regime.


It’s called “Simple” for a reason: PyEdit (ahead)


Finally, before you change your system registry to make SimpleEditor your default text
file viewer, I should mention that although it shows the basics, it’s something of a
stripped-down version (really, a prototype) of the PyEdit example we’ll meet in Chap-
ter 11. In fact, you may wish to study that example now if you’re looking for more
complete tkinter text-processing code in general. There, we’ll also use more advanced
text operations, such as the undo/redo interface, case-insensitive searches, external files
search, and more. Because the Text widget is so powerful, it’s difficult to demonstrate
more of its features without the volume of code that is already listed in the PyEdit
program.


I should also point out that SimpleEditor not only is limited in function, but also is just
plain careless—many boundary cases go unchecked and trigger uncaught exceptions
that don’t kill the GUI, but are not handled or reported well. Even errors that are caught
are not reported to the user (e.g., a paste with nothing to be pasted). Be sure to see the
PyEdit example for a more robust and complete implementation of the operations
introduced in SimpleEditor.


Unicode and the Text Widget


I told you earlier that text content in the Text widget is always a string. Technically,
though, there are two string types in Python 3.X: str for Unicode text, and bytes for
byte strings. Moreover, text can be represented in a variety of Unicode encodings when
stored on files. It turns out that both these factors can impact programs that wish to
use Text well in Python 3.X.


538 | Chapter 9: A tkinter Tour, Part 2

Free download pdf