问题描述
我一直在尝试将回调绑定到菜单项选择,而不是使用 add_command 方法的 command= 功能.
I've been trying to bind a callback to a menu item selection, instead of using the command= functionality of the add_command method.
但是,似乎无论我尝试什么,它都只会在选择菜单项(菜单 1"和菜单 2")时为我提供正确的索引,而不是菜单项的按钮索引菜单.当按钮被按下时,将只打印 None.
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()
以防万一,我使用的是带有 Python 3.4 的 Windows 7
In case it matters, I'm on Windows 7 with Python 3.4
推荐答案
如果希望事件在下拉菜单上触发,则需要为每个菜单添加相同的绑定.
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).
这篇关于<<MenuSelect>>的使用方法绑定到 tkinter 菜单项选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!