Tkinter Text Undo and Redo
The Text control has a simple recovery (undo) and redo (redo) mechanism that can be applied to text deletion (delete) and text insertion (insert). the Text control does not have this mechanism turned on in the default environment. to use this mechanism, you can add the undo=True parameter inside the Text( ) method.
Example#1
Add a toolbar with Undo and Redo function buttons within this toolbar to perform Undo and Redo jobs respectively.
from tkinter import *
from tkinter import messagebox
def cutJob(): # Cut Method
print("Cut operation in progress...")
text.event_generate("<<Cut>>")
def copyJob():
print("Copy operation in process...")
text.event_generate("<<Copy>>")
def pasteJob():
print("Paste operation is in progress...")
text.event_generate("<<Paste>>")
def showPopupMenu(event):
print("Show pop-up menu...")
popupmenu.post(event.x_root,event.y_root)
def undoJob():
try:
text.edit_undo()
except:
print("No previous action")
def redoJob():
try:
text.edit_redo()
except:
print("No previous action")
root = Tk()
root.title("apidemos.com")
root.geometry("300x180")
popupmenu = Menu(root,tearoff=False)
# Create a list of three commands in the pop-up menu
popupmenu.add_command(label="Cut",command=cutJob)
popupmenu.add_command(label="Copy",command=copyJob)
popupmenu.add_command(label="Paste",command=pasteJob)
# Click on the right mouse button binding to display the pop-up menu
root.bind("<Button-3>",showPopupMenu)
# Create Toolbar
toolbar = Frame(root,relief=RAISED,borderwidth=1)
toolbar.pack(side=TOP,fill=X,padx=2,pady=1)
# Create Button
undoBtn = Button(toolbar,text="Undo",command=undoJob)
undoBtn.pack(side=LEFT,pady=2)
redoBtn = Button(toolbar,text="Redo",command=redoJob)
redoBtn.pack(side=LEFT,pady=2)
# Create Text
text = Text(root,undo=True)
text.pack(fill=BOTH,expand=True,padx=3,pady=2)
text.insert(END,"Five Hundred Miles\n") # Set Tag at the same time when inserting
text.insert(END,"If you miss the rain I'm on,\n")
text.insert(END,"You will know that I am gone.\n")
text.insert(END,"You can hear the whistle blow\n")
text.insert(END,"A hundred miles,\n")
root.mainloop()
Output:
When we add the undo=True parameter to the Text( ) constructor on line 46, the edit_undo( ) method can be called with the text object on line 14 of the program, and this method will automatically perform the Undo action. Line 19 of the program will call the edit_redo( ) method with the text object, and this method will automatically perform the Redo action.