假设一个菜单按钮包含两个子菜单(Tree1和Tree2)。每个子菜单包含两个选项:"梨"one_answers";Apple"。有没有办法知道从哪棵树(子菜单)有一个"梨"?是别人摘的吗?
import tkinter as tk
root = tk.Tk()
def F_WhatsTheTree(event):
# This should tell me the tree from which the selected fruit comes
return
# I create a menubutton with a menu inside
menubutton = tk.Menubutton(root, text="Menu")
menubutton.menu = tk.Menu(menubutton, tearoff=0)
menubutton["menu"] = menubutton.menu
# then I create two submenus
menubutton.menu.submenu1 = tk.Menu(menubutton.menu, tearoff=0)
menubutton.menu.submenu2 = tk.Menu(menubutton.menu, tearoff=0)
# add some cascades to them
menubutton.menu.add_cascade(label="Tree1", menu=menubutton.menu.submenu1)
menubutton.menu.add_cascade(label="Tree2", menu=menubutton.menu.submenu2)
# then some fruits
menubutton.menu.submenu1.add_radiobutton(label="Pear")
menubutton.menu.submenu1.add_radiobutton(label="Apple")
menubutton.menu.submenu2.add_radiobutton(label="Pear")
menubutton.menu.submenu2.add_radiobutton(label="Apple")
# I pack the whole thing
menubutton.pack()
root.bind("<Button-3>", F_WhatsTheTree)
root.mainloop()
我试过这样做:
def F_WhatsTheTree(event):
for i in range(len(menubutton.menu.winfo_children())):
Submenu = menubutton.menu.winfo_children()[i]
for j in range(Submenu.index("end")+1):
if Submenu.index(j) == Submenu.index("active"):
#I have also tried:
#Submenu.index(tk.ACTIVE)
#Submenu.index(tk.CURRENT)
print("The damn tree is: "+Submenu)
…但是我不知道如何引用"selected"。选项或"已选"选项。单选按钮的状态。
我一直在阅读菜单和单选按钮的文档,试图找到一种方法来做到这一点,但我什么也没得到(显然)。
任何帮助都将是非常感激的。
我建议给每个单选按钮一个不同的值。
例如:
...submenu1.add_radiobutton(label="Pear" value="submenu1.pear")
...submenu1.add_radiobutton(label="Apple", value="submenu1.apple")
...menu.submenu2.add_radiobutton(label="Pear", value="submenu2.pear")
...menu.submenu2.add_radiobutton(label="Apple", value="submenu2.apple")
然后,在使用该值的代码中,你可以去掉句点之前的所有内容,以知道它来自哪个菜单。