Tkinter's Text widget comes with some handy built-in functionality to handle common text-related functions. Let's leverage these functionalities to implement some common features in our text editor.
Clearly the text widget comes built in with these events. Rather than coding these functions ourselves, let's use the built-in functions to add these features to our text editor.
The documentation of Tcl/Tk "universal widget methods" tells us that we can trigger events without any external stimulus using the following command:
widget.event_generate(sequence, **kw)
To trigger the cut event for our textPad
widget, all we need is a line of code such as the following:
textPad.event_generate("<<Cut>>")
Let's call that using a function cut, and associate it with our cut menu using the command callback. See the code 2.03.py
that bears the following code:
def cut(): textPad.event_generate("<<Cut>>") # then define a command callback from our existing cut menu like: editmenu.add_command(label="Cut", compound=LEFT, image=cuticon, accelerator='Ctrl+X', command=cut)
Similarly, we trigger the copy and paste functions from their respective menu items.
-undo
option as true
. To leverage this option, let's first set the Text widget's undo
option to true
as shown in the following screenshot:textPad = Text(root, undo=True)
Now if you open your text editor and try out the undo and redo features using Ctrl + Z and Ctrl + Y, you will see that they work fine. We now only have to associate the events to functions and callback the functions from our Undo and Redo menus respectively. This is similar to what we did for cut, copy, and paste. Refer to the code in 2.03.py
.
18.222.184.200