Reputation: 613
I want to implement a 2-layer menu and press Confirm
button to show its parent menu label and its value. Now I can get its value but have no idea how to get its parent menu label.
Please advise. Thank you.
import tkinter
def get_selection(menu, var):
print('Menu: ' + menu.entrycget(0, "label")) # How to get this ?
print('Item: ' + var.get())
items = [['A', 'Apple', 'Amazon'], ['T', 'T-Mobile', 'Tesla']]
root = tkinter.Tk()
var = tkinter.StringVar(value='--')
menu_button = tkinter.Menubutton(
root, textvariable=var, borderwidth=1, relief='raised')
main_menu = tkinter.Menu(menu_button, tearoff=False)
menu_button.configure(menu=main_menu)
for item in items:
menu = tkinter.Menu(main_menu, tearoff=False)
main_menu.add_cascade(label=item[0], menu=menu)
for value in item[1:]:
menu.add_radiobutton(value=value, label=value, variable=var)
menu_button.pack(fill=tkinter.BOTH, side=tkinter.TOP)
tkinter.Button(
command=lambda: get_selection(menu, var),
text='Confirm').pack(fill=tkinter.BOTH, side=tkinter.BOTTOM)
root.mainloop()
Expected Output
# Case 1
Menu: A
Item: Apple
# Case 2
Menu: T
Item: Tesla
Actual Output
# Case 1
Menu: T-Mobile
Item: Apple
# Case 2
Menu: T-Mobile
Item: Tesla
Upvotes: 1
Views: 93
Reputation: 47093
Since you use same variable menu
for all the cascade menu, so it finally refers to the last menu added.
You can use the text of the selected item to look up the required data in items
:
def get_selection(var):
value = var.get()
menu = ""
for item in items:
if value in item:
menu = item[0]
break
print('Menu: ' + menu)
print('Item: ' + value)
...
tkinter.Button(command=lambda: get_selection(var), text='Confirm').pack(fill=tkinter.BOTH, side=tkinter.BOTTOM)
Upvotes: 2