How do I keep style information (tags) when undoing and redoing in a Tkinter Text?

95 Views Asked by At

I am writing an html editor in Python 3.7.4 / Tkinter 8.6 / Windows 10.0.18362.356, and am using tags to style text for <em>, <strong> etc. However, the inbuilt undo/redo mechanism deletes these tags, for instance, if I redo immediately after undoing. Before I go nuts trying to implement my own undo/redo mechanism, is there something I'm missing?

import tkinter
import tkinter.font

def bold(event=None):
    try:
        textbox.tag_add('bold', 'sel.first', 'sel.last')
    except tkinter.TclError:
        textbox.tag_add('bold', 1.0, 'end')

textbox = tkinter.Text(undo=True)
boldness = tkinter.font.Font(weight='bold')
textbox.tag_config('bold', font=boldness)
textbox.bind('<Control-b>', bold)
textbox.grid()
textbox.mainloop()

Now:

  1. Run the program.

  2. Insert the text Hello, World! into the textbox.

  3. Select the text lo, Wo using the mouse.

  4. Press ctrl-b. The selected text becomes bold.

  5. Press ctrl-z. Some or all of the text disappears.

  6. Press ctrl-y. The text reappears.

Now, I expected from using other word processing programs, that the text would still be tagged when it reappears. However, it is not.

Thanks.

0

There are 0 best solutions below