Adding bind_insert, bind_delete methods to the Text widget
July 1998 | Fredrik Lundh
An old proposal from July 1998. I wonder what happened to the sample implementation…What do you think about adding the following new methods to the Text class:
def bind_insert(self, callback) def bind_delete(self, callback)
If installed, the given callbacks are called upon each call to “insert” (“delete”) generated by the standard text widget bindings, calls to Tkinter (outside the callbacks themselves), calls to Tcl code, etc. The callback is called before the insert/delete operation is actually executed, and you can return “break” to “capture” the operation.
This makes it trivial to implement “dirty” flags, undoable text widgets, readonly text regions, etc. Here’s a simple example:
class UndoableText(Text): def __init__(...) ... self.bind_insert(self.insert_hook) self.bind_delete(self.delete_hook) self.bind("<Control-z>", self.undo) self.history = [] def insert_hook(self, index, text, *tags): self.history.append(1, self.index(index), len(text)) def delete_hook(self, start, stop=None): self.history.append(0, self.index(index), self.get(start, stop)) def undo(self, event): ...
Guido says: One API design question: I think this should be done as a subclass of Tkinter.Text, possibly even in a different module, rather than by defining new methods on the Text class; that would violate the (informal) more-or-less direct mapping between Python method names and Tk subcommands.