Store menu in Tkinter

I want the cascade menu to be open after pressing the control button in the cascade. Thus, it basically closes only when the user clicks elsewhere (as is usually the case). It seems that it cannot find a suitable option or way to open the specified menu in the callback. Does the invoke () function only work on buttons with a cascade on the right? How would you do that?

+4
source share
1 answer

Yes, I know that this was asked a long time ago, but I was curious if there was a way to do this using tkinter, so I was a little silent and figured out how to do it. I could not think of a way to correctly place the permanent menu where it was when it was open, but I managed to save it in any place you request (I use the upper left corner of the root window). And yes, I know that this is not a good, correct implementation based on classes, but I was just going as a simple test, because I could write without obscuring it with too many extraneous details.

try: from tkinter import * from tkinter.ttk import * except: from Tkinter import * from ttk import * root = Tk() var = StringVar() def menu_click(menu, item): global root var.set(item) menu.post(root.winfo_rootx(), root.winfo_rooty()) root.option_add('*tearOff', False) # remove tearoff from all menus Label(root, textvariable=var).pack() # just to give menu clicks some feedback root.geometry('400x300') menubar = Menu(root) root['menu'] = menubar menu_test = Menu(menubar) menubar.add_cascade(menu=menu_test, label='Test') menu_test.add_command(label='One', command=lambda: menu_click(menu_test, 'One')) menu_test.add_command(label='Two', command=lambda: menu_click(menu_test, 'Two')) menu_test.add_command(label='Three', command=lambda: menu_click(menu_test, 'Three')) menu_cas = Menu(menu_test) menu_test.add_cascade(menu=menu_cas, label='Four') menu_cas.add_command(label='One', command=lambda: menu_click(menu_cas, 'Fourty One')) menu_cas.add_command(label='Two', command=lambda: menu_click(menu_cas, 'Fourty Two')) menu_cas.add_command(label='Three', command=lambda: menu_click(menu_cas, 'Fourty Three')) root.mainloop() 
+3
source

Source: https://habr.com/ru/post/1369655/


All Articles