4

I was trying to use undo function on my text widget in tkinter but without any luck. I tried it this way:

from Tkinter import *
from ttk import Notebook

def OnVsb(*args):
    text.yview(*args)
    numbers.yview(*args)

def OnMouseWheel(event):
    text.yview("scroll", event.delta,"units")
    numbers.yview("scroll",event.delta,"units")
    return "break"

def undo(*argv):
    text.edit_undo()

root = Tk()
defaultbg = root.cget('bg')
root.bind('<Control-z>', undo)
note = Notebook(root)
frame = Frame(note, bd=5, relief=GROOVE, padx=5, pady=5)
frame.pack()
bar = Scrollbar(frame, command=OnVsb)
bar.pack(side=RIGHT, fill=Y)
numbers = Listbox(frame, width=5, height=30,bg=defaultbg,relief=FLAT,   yscrollcommand=bar.set)
numbers.pack(side=LEFT, fill=Y)
text = Text(frame,bd=3, width=145, height=30, yscrollcommand=bar.set)
text.pack(side=LEFT, fill=Y) 
text.bind("<MouseWheel>", OnMouseWheel)
text.tag_config("attr", foreground="tomato")
text.tag_config("value", foreground="dark violet")
text.tag_config("tags", foreground="dodger blue")
text.tag_config("text", font=("Georgia", "9", "bold"))
text.focus_set()
root.lift()
root.call('wm', 'attributes', '.', '-topmost', '1')
root.after_idle(root.call, 'wm', 'attributes', '.', '-topmost', False)
root.mainloop()

But for some reason it does nothing. I thought it was implemented by default in text widget, but it didn't work out. Any suggestions on how to use this feature on a text widget? Any example would be much appreciated.

midori
  • 4,807
  • 5
  • 34
  • 62

2 Answers2

11

Ok, i found the information finally.

All i was needed is to set undo to True when i initialized text widget, just like this:

text = Text(frame,bd=3, width=145, height=30, yscrollcommand=bar.set, undo=True)

There is no need for undo function and text.bind. It works automatically when undo is True.

midori
  • 4,807
  • 5
  • 34
  • 62
  • 1
    That's the correct solution, working perfectly well even with a `ScrolledText` widget! And for anyone else wondering, enabling undo also enables redo. – gaborous Mar 14 '20 at 00:05
0

In Python 2, you must set the undo keyword arg to True to activate the undo/redo stack. In Python 3 (at least 3.6), the stack is activated by default.

GaryMBloom
  • 5,350
  • 1
  • 24
  • 32