Undo and redo features in a Tkinter Text widget

Tkinter Text widget is a multiline input widget that accepts text input from users. To add undo and redo functionality, we need to enable the undo parameter and use specific keyboard shortcuts or methods.

Basic Undo/Redo Setup

Enable undo functionality by setting undo=True when creating the Text widget ?

import tkinter as tk

# Create main window
root = tk.Tk()
root.title("Undo/Redo Example")
root.geometry("500x400")

# Create Text widget with undo enabled
text_widget = tk.Text(root, width=50, height=15, undo=True)
text_widget.pack(pady=20)

# Insert some initial text
text_widget.insert(tk.END, "Type here and try Ctrl+Z (undo) or Ctrl+Y (redo)")

root.mainloop()

Keyboard Shortcuts

The Text widget automatically supports these keyboard shortcuts when undo=True ?

Shortcut Action Description
Ctrl+Z Undo Reverses the last action
Ctrl+Y Redo Restores the undone action

Programmatic Undo/Redo Methods

You can also trigger undo/redo operations programmatically using built-in methods ?

import tkinter as tk

root = tk.Tk()
root.title("Programmatic Undo/Redo")
root.geometry("500x400")

# Text widget with undo enabled
text_widget = tk.Text(root, width=50, height=15, undo=True)
text_widget.pack(pady=10)

# Add some initial text
text_widget.insert(tk.END, "Edit this text to test undo/redo functionality")

# Function to undo
def undo_action():
    try:
        text_widget.edit_undo()
    except tk.TclError:
        print("Nothing to undo")

# Function to redo
def redo_action():
    try:
        text_widget.edit_redo()
    except tk.TclError:
        print("Nothing to redo")

# Create buttons
button_frame = tk.Frame(root)
button_frame.pack(pady=10)

undo_btn = tk.Button(button_frame, text="Undo", command=undo_action)
undo_btn.pack(side=tk.LEFT, padx=5)

redo_btn = tk.Button(button_frame, text="Redo", command=redo_action)
redo_btn.pack(side=tk.LEFT, padx=5)

root.mainloop()

Key Points

  • Set undo=True when creating the Text widget
  • Use edit_undo() and edit_redo() methods programmatically
  • Handle TclError exceptions when no undo/redo operations are available
  • The undo stack maintains a history of text modifications

Conclusion

Enable undo/redo in Tkinter Text widgets by setting undo=True. Users can press Ctrl+Z/Ctrl+Y or you can call edit_undo() and edit_redo() methods programmatically.

---
Updated on: 2026-03-25T23:34:14+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements