Skip to content Skip to sidebar Skip to footer

How To Open A Menu Programmatically In Python Tkinter?

I have a graphical user interface with a menubar. I would like to be able to open those menus programmatically as if a user had clicked on them. My first guess was invoke but that

Solution 1:

The invoke command is equivalent to tearoff. If you allowed tearoff you would see that work.

The command you are looking for is 'postcascade'. There is no tkinter binding to this command, and if you call it manually (root.tk.eval(str(mb)+' postcascade 1') nothing happens, which is probably why there is no binding.

I tried many other things but I could not get this to work.

However, tk has a Menubutton widget too, and that responds to the <<Invoke>> event. So (if you really really want this functionality) you can make your own menubar:

import Tkinter as tk
import ttk

def log(command):
    print 'running {} command'.format(command)

class MenuBar(tk.Frame):
    def __init__(self, master=None):
        tk.Frame.__init__(self, master, bd=1, relief=tk.RAISED)

        file_btn = tk.Menubutton(self, text='File')
        menu_file = tk.Menu(file_btn, tearoff=False)
        menu_file.add_command(label='save', command=lambda: log('save'))
        menu_file.add_command(label='open', command=lambda: log('open'))
        file_btn.config(menu=menu_file)
        file_btn.pack(side=tk.LEFT)
        master.bind('f', lambda e: file_btn.event_generate('<<Invoke>>'))

        edit_btn = tk.Menubutton(self, text='Edit')
        menu_edit = tk.Menu(edit_btn, tearoff=False)
        menu_edit.add_command(label='add', command=lambda: log('add'))
        menu_edit.add_command(label='remove', command=lambda: log('remove'))
        edit_btn.config(menu=menu_edit)
        edit_btn.pack(side=tk.LEFT)
        master.bind('e', lambda e: edit_btn.event_generate('<<Invoke>>'))

m = tk.Tk()
m.geometry('300x300')
mb = MenuBar(m)
mb.pack(side=tk.TOP, fill=tk.X)
m.mainloop()

Once the menu is opened with the hotkey, it can be navigated with the arrow keys, the selected option can be run with the enter key, or closed with the escape key.

Post a Comment for "How To Open A Menu Programmatically In Python Tkinter?"