In this last iteration, we will add the following features to our editor:
Let us complete our editor in this final iteration.
textPad.bind('<Control-N>', new_file) textPad.bind('<Control-n>', new_file) textPad.bind('<Control-O>', open_file) textPad.bind('<Control-o>', open_file) textPad.bind('<Control-S>', save) textPad.bind('<Control-s>', save) textPad.bind('<Control-A>', select_all) textPad.bind('<Control-a>', select_all) textPad.bind('<Control-f>', on_find) textPad.bind('<Control-F>', on_find) textPad.bind('<KeyPress-F1>', help_box)
Simply adding these lines takes care of our event bindings. However, this introduces a new issue for us. We have already discussed that event bindings pass the event object as a parameter to the bound callback. None of our previous functions are equipped to handle the incoming parameters. To do that we need to add the event=None
parameter.
Adding this optional argument allows us to use these functions with or without the event parameter.
Alternatively, you can also add textPad.bind (event, lambda e: callback())
to ignore the event
argument altogether.
Now you can access these functions using your keyboard shortcuts.
Note that we did not bind keyboard shortcuts for cut, copy, and paste. This is because the Text widget comes with automatic binding for these events. If you add bindings for these events, it will cause cut, copy, and paste events to take place twice; once from the built-in widget and once from your own defined event handler.
The menu that pops up on the right-mouse-button click at the location of the mouse cursor is called the context menu or the o. This is shown in the following screenshot:
Let's code this feature in our text editor. We first define our context menu:
cmenu = Menu(textPad) for i in ('cut', 'copy', 'paste', 'undo', 'redo'): cmd = eval(i) cmenu.add_command(label=i, compound=LEFT, command=cmd) cmenu.add_separator() cmenu.add_command(label='Select All', underline=7, command=select_all)
We then bind the right-click of a mouse with a callback named popup
:
textPad.bind("<Button-3>", popup)
Finally, we define the method popup
:
def popup(event):
cmenu.tk_popup(event.x_root, event.y_root, 0)
root.iconbitmap('icons/pypad.ico')
18.227.10.45