Search code examples
python-2.7tkintertkinter-menu

Getting a list (or dict, or tuple) of entries in a Tkinter menu widget


My environment is Python 2.7, running on Windows 10.

I'm writing a Tkinter application which is going to include a "recent files" menu for the user's convenience. To create that menu I not only need the ability to add, delete, and re-order menu entries dynamically, but also to identify how many entries are present, and what those entries are. I want this to support the logic that will "cap" the file listing to (say) the five most recent files, deleting the older ones as new files are added to the list. It would also support the ability to "clear history", deleting all the existing entries.

Adding, deleting, and re-ordering the menu content for a single known item is a nobrainer; the add_command(), delete(), and insert_command() methods will cover these use cases. But I've checked several online references and I can't locate a method or attribute that will tell me the current content of the menu, or even one to tell me how many entries the menu currently contains.

Do such attributes/methods exist? Or must I apply a sledgehammer approach, like repeatedly executing the entrycget() method index-by-index until it encounters an exception?


Solution

  • You can use the index method with a parameter of "end" to get the index of the last item.

    last_item = the_menu.index('end')
    

    You can then use that to iterate over all of the items in a menu.