Search code examples
pythontkintertkinter-text

Is there are a Python Tkinter method in the Text widget for joining the Undo/Redo stack?


I am seeking a method that can have the functionality of joining the undo/redo stack of the Tkinter Text widget written in the Python language. Is there something like the method to merging the user input undo/redo stack programmatically, or merging the programmatic changes to the Tkinter Text widget programmatically?

For example, I want to have the following:

import tkinter as tk

root = tk.Tk()
root.title("Stackoverflow question")

text = tk.Text(root)

text.some_method()
text.insert(tk.END, "a")
text.insert(tk.END, "b")
text.insert(tk.END, "c")
text.reversing_method()

text.pack()

root.mainloop()

As you can see, after calling some_method, the user will have undone the whole string "abc" (and of course, after redo the steps, the string "abc" will be back again in pairs but not in sequence of "a", "b", and "c") after the text is entered programmatically (and by user). However, I would like to seek a method also, when the reversing_method is called, the user can undo the text entered programmatically or by them single-by-single.


Solution

  • You may.

    If you are using Tkinter versioned >= 8.5 (so far I have known as I'm using Tkinter version 8.6 and your operating system may be vary; however, I guess the following methods are compatible with Tkinter versioned <= 8.4)

    • Replace your some_method with text.config(autoseparators=False); and
    • Replace your reverse_method with text.config(autoseparators=True).

    P.S. If you want to add the undo/redo stack programmatically and manually, you may use the method text.edit_separator().

    MRE:

    import tkinter as tk
    
    root = tk.Tk()
    root.title("StackOverflow answer from Misinahaiya")
    
    text = tk.Text()
    text.config(autoseparators=False) # or .configure as you like
    #...
    text.config(autoseparators=True) # the default, as the reversing method
    
    root.mainloop()