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

(yzsuai) #1

In short, tkinter’s Text and other text-related widgets such as Entry support display of
International character sets for both str and bytes, but we must pass decoded Unicode
str to support the broadest range of character types. In this section, we decompose the
text story in tkinter in general to show why.


String types in the Text widget


You may or may not have noticed, but all our examples so far have been representing
content as str strings—either hardcoded in scripts, or fetched and saved using simple
text-mode files which assume the platform default encoding. Technically, though, the
Text widget allows us to insert both str and bytes:


>>> from tkinter import Text
>>> T = Text()
>>> T.insert('1.0', 'spam') # insert a str
>>> T.insert('end', b'eggs') # insert a bytes
>>> T.pack() # "spameggs" appears in text widget now
>>> T.get('1.0', 'end') # fetch content
'spameggs\n'

Inserting text as bytes might be useful for viewing arbitrary kinds of Unicode text,
especially if the encoding name is unknown. For example, text fetched over the Internet
(e.g., attached to an email or fetched by FTP) could be in any Unicode encoding; storing
it in binary-mode files and displaying it as bytes in a Text widget may at least seem to
side-step the encoding in our scripts.


Unfortunately, though, the Text widget returns its content as str strings, regardless of
whether it was inserted as str or bytes—we get back already-decoded Unicode text
strings either way:


>>> T = Text()
>>> T.insert('1.0', 'Textfileline1\n')
>>> T.insert('end', 'Textfileline2\n') # content is str for str
>>> T.get('1.0', 'end') # pack() is irrelevent to get()
'Textfileline1\nTextfileline2\n\n'

>>> T = Text()
>>> T.insert('1.0', b'Bytesfileline1\r\n') # content is str for bytes too!
>>> T.insert('end', b'Bytesfileline2\r\n') # and \r displays as a space
>>> T.get('1.0', 'end')
'Bytesfileline1\r\nBytesfileline2\r\n\n'

In fact, we get back str for content even if we insert both str and bytes, with a single
\n added at the end for good measure, as the first example in this section shows; here’s
a more comprehensive illustration:


>>> T = Text()
>>> T.insert('1.0', 'Textfileline1\n')
>>> T.insert('end', 'Textfileline2\n') # content is str for both
>>> T.insert('1.0', b'Bytesfileline1\r\n') # one \n added for either type
>>> T.insert('end', b'Bytesfileline2\r\n') # pack() displays as 4 lines
>>> T.get('1.0', 'end')
'Bytesfileline1\r\nTextfileline1\nTextfileline2\nBytesfileline2\r\n\n'

Text | 539
Free download pdf