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

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.

主站蜘蛛池模板: 桦甸市| 刚察县| 太康县| 黔江区| 永春县| 沾化县| 深泽县| 扎鲁特旗| 垣曲县| 灵台县| 和田县| 潞西市| 麻城市| 北票市| 甘孜县| 阿荣旗| 晋宁县| 大连市| 郁南县| 平定县| 青川县| 邹城市| 承德县| 都昌县| 泸西县| 凤城市| 北辰区| 莱芜市| 铁力市| 栾川县| 安宁市| 丰都县| 扎囊县| 吐鲁番市| 峡江县| 达孜县| 马关县| 武功县| 禄丰县| 临沂市| 高清|