官术网_书友最值得收藏!

Creating a context/pop-up menu

Let's complete the editor in this final iteration by adding a contextual menu to the editor (2.12.py), as shown in the following screenshot:

The menu that pops up on a right-click at the location of the cursor is called the context menu or the pop-up menu.

Let's code this feature in the text editor. First, define the context menu, as follows:

popup_menu = Menu(content_text)
for i in ('cut', 'copy', 'paste', 'undo', 'redo'):
cmd = eval(i)
popup_menu.add_command(label=i, compound='left', command=cmd)
popup_menu.add_separator()
popup_menu.add_command(label='Select All',underline=7, command=select_all)

Then, bind the right-click of a mouse with a callback named show_popup_menu, as follows:

content_text.bind('<Button-3>', show_popup_menu)

Finally, define the show_popup_menu function in the following way:

def show_popup_menu(event):
popup_menu.tk_popup(event.x_root, event.y_root)

You can now right-click anywhere on the Text widget in the editor to open the contextual menu.

This concludes the iteration as well as the chapter.

主站蜘蛛池模板: 建平县| 蒙城县| 巫山县| 蒲城县| 九龙县| 贡觉县| 宜良县| 郓城县| 临泉县| 博客| 施秉县| 修水县| 和政县| 甘泉县| 宣威市| 曲周县| 苍溪县| 池州市| 安康市| 泰和县| 桐梓县| 永和县| 于田县| 铜陵市| 富顺县| 拜城县| 南京市| 洪湖市| 河源市| 万盛区| 云南省| 个旧市| 聂拉木县| 晋州市| 松原市| 漳平市| 宾川县| 五河县| 临漳县| 甘谷县| 岑巩县|