Tkinter+ backspace characters (and an re.sub problem)

Fredrik Lundh fredrik at pythonware.com
Thu Dec 20 03:33:31 EST 2001


David Mallwitz wrote:
>     The Tkinter Text widget doesn't understand '\b' or '\x08' as the
> backspace character when sent a string containing either of them. Nor does
> it understand '^H' as a substitute for '\b'.
>     I've done some googling, but haven't found a solution other than doing a
> regexp sub on the string before sending it to the text widget. That seemed
> like a good idea, but I'm not able to construct the regexp in a way that
> will handle stacked backspace characters.
>     Any ideas on how to tell the widget to process a backspace? Or on how to
> construct an RE that will match multiple '\b's?

something like this should work:

from Tkinter import *
import re

message = 'all work and no play makes Jack\x08\x08\x08\x08Dave a dull boy'

text = Text()
text.pack()

# find backspace/non-backspace runs
for fragment in re.findall("\x08+|[^\x08]+", message):
    if fragment[0] == "\x08":
        # delete len(fragment) characters before current insertion point
        text.delete("%s-%dc" % (INSERT, len(fragment)), INSERT)
    else:
        text.insert(INSERT, fragment)

mainloop()

</F>

<!-- (the eff-bot guide to) the python standard library:
http://www.pythonware.com/people/fredrik/librarybook.htm
-->





More information about the Python-list mailing list