Leveraging the power of built-in Text widget options

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.

Engage Thrusters

  1. Let's start by implementing the Cut, Copy, and Paste features. We now have our editor GUI ready. If you open the program and play with the Text widget, you will notice that you can perform basic functions such as cut, copy, and paste in the text area using the keyboard shortcuts Ctrl + X, Ctrl + C, and Ctrl + V. All these functions exist without us having to add a single line of code toward these functionalities.

    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.

  2. Next we will move on to implementing the undo and redo features. The Tcl/Tk text documentation tells us that the Text widget has an unlimited undo and redo mechanism, provided we set the -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.

Objective Complete – Mini Briefing

Taking advantage of some built-in Text widget options, we have successfully implemented the functionality of cut, copy, paste, undo, and redo into our text editor with minimal coding.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.184.200