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.
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.
Share Improve this question asked Jan 19 at 4:38 ManngoManngo 16.3k13 gold badges102 silver badges143 bronze badges 2 |2 Answers
Reset to default 1You 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)
Checkout Using dictionary to make Option menu and receive the values on selection, with tkinter, it is a similar situation to what you are trying to do with dictionaries. Hope this helps :)
insert_cascade()
mentioned. Thanks. – Manngo Commented Jan 19 at 7:26