This is an unofficial mirror of Tkinter reference documentation (based on Python 2.7 and Tk 8.5) created by the late John Shipman.
It was last updated in 2013 and is unmaintained. [More info]
The Text
widget has a built-in mechanism
that allows you to implement undo and redo operations
that can cancel or reinstate changes to the text within
the widget.
Here is how the undo/redo stack works:
Every change to the content is recorded by pushing entries onto the stack that describe the change, whether an insertion or a deletion. These entries record the old state of the contents as well as the new state: if a deletion, the deleted text is recorded; if an insertion, the inserted text is recorded, along with a description of the location and whether it was an insertion or a deletion.
Your program may also push a special record called a separator onto the stack.
An undo operation changes the contents of the widget to what they were at some previous point. It does this by reversing all the changes pushed onto the undo/redo stack until it reaches a separator or until it runs out of stack.
However, note that Tkinter also remembers how much of the stack was reversed in the undo operation, until some other editing operation changes the contents of the widget.
A redo operation works only if no editing operation has occurred since the last undo operation. It re-applies all the undone operations.
For the methods used to implement the undo/redo stack,
see the .edit_redo
, .edit_reset
, .edit_separator
, and
.edit_undo
methods in Section 24.8, “Methods on Text
widgets”. The undo mechanism is not
enabled by default; you must set the undo
option in the widget.