How to use <<MenuSelect>> to bind to a tkinter menu item selection

帅比萌擦擦* 提交于 2019-12-12 02:25:55

问题


I've been trying to bind a callback to a menu item selection, instead of using the command= functionality of the add_command method.

However, it seems that no matter what I try it will only give me a proper index of the menu item ("Menu 1" and "Menu 2") when they are select, instead of the index of the buttons of the menu. When the button is pressed in will just print None.

This is my current test code, but I've been trying a bunch of different stuff.

import tkinter as tk

def menucallback(event):
    print(root.call(event.widget, "index", "active"))

root = tk.Tk()

# create menu
menubar = tk.Menu(root)
menu1 = tk.Menu(menubar, tearoff=0)
menu1.add_command(label="Button 1")
menu1.add_command(label="Button 2")
menubar.add_cascade(label="Menu 1", menu=menu1)

menu2 = tk.Menu(menubar, tearoff=0)
menu2.add_command(label="Button 6")
menu2.add_command(label="Button 7")

menubar.add_cascade(label="Menu 2", menu=menu2)

tk.Tk.config(root, menu=menubar)

# bind to function
menubar.bind("<<MenuSelect>>", menucallback)

root.mainloop()

In case it matters, I'm on Windows 7 with Python 3.4


回答1:


If you want the event to trigger on the dropdown menus, you need to add the same binding to each menu.

The reason you get none when selecting the menu item is likely because the state of the menu changes before the callback is called (ie: there is no active item after you click).



来源:https://stackoverflow.com/questions/33132486/how-to-use-menuselect-to-bind-to-a-tkinter-menu-item-selection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!