How to use <> to bind to a tkinter

2019-09-11 02:32发布

问题:

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).