Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
816 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...