最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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
  • Have you already checked this question? – Steve Commented Jan 19 at 7:10
  • I have now, and it indirectly answers this one, although the question was about what went wrong. I did spend some time looking for such as this, but that question is the first time I have seen insert_cascade() mentioned. Thanks. – Manngo Commented Jan 19 at 7:26
Add a comment  | 

2 Answers 2

Reset to default 1

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)

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 :)

发布评论

评论列表(0)

  1. 暂无评论