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

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.

主站蜘蛛池模板: 安宁市| 胶州市| 广安市| 托克逊县| 祁东县| 柳河县| 德阳市| 长治市| 通江县| 绩溪县| 阆中市| 玉门市| 沽源县| 宿迁市| 金寨县| 德格县| 墨竹工卡县| 朝阳市| 双流县| 耿马| 安泽县| 怀安县| 正镶白旗| 平顶山市| 铅山县| 新干县| 海宁市| 历史| 阿瓦提县| 手机| 墨脱县| 济南市| 红桥区| 景宁| 景宁| 莒南县| 滦平县| 鸡西市| 尖扎县| 东乌珠穆沁旗| 亳州市|