pythontkintermenu

How can I add a menu before the first in Python tkInter?


I’m writing some code to add a menu to a tkInter application. Here is a working sample:

import tkinter

main = tkinter.Tk()
main.title('Menu Test')

menubar = tkinter.Menu(main)
main['menu'] = menubar

m = tkinter.Menu()
menubar.add_cascade(menu=m, label='First')
m.add_command(label='Thing', command=lambda: print('thing'))

m = tkinter.Menu()
menubar.add_cascade(menu=m, label='Second')
m.add_command(label='Whatever', command=lambda: print('whatever'))

#   How to add another menu before 'First' ?

main.mainloop()

Is it possible to add another menu before the first menu (First) ?

Obviously, in this simple case, I can simply define it first, but I want to write a routine which populates a menu from a dictionary.


Solution

  • You can use standard tk method insert rather than add_cascade. The first argument is a menu index, and the new item will be added before that index. For the index you could use a numerical index (eg: 0 to represent the first item) or the menu name "First":

    m = tkinter.Menu()
    menubar.insert(0, "cascade", label="Third", menu=m)
    

    -or-

    m = tkinter.Menu()
    menubar.insert("First", "cascade", label="Third", menu=m)
    

    There is also a insert_cascade method unique to tkinter (verses the tk toolkit in other languages):

    m = tkinter.Menu()
    menubar.insert_cascade("First", label="Third", menu=m)