pythonpython-3.xtkintertkinter-menu

How to check if Menu item exists in Python Tkinter


On python tkinter I have the following code for creating a Menu with only 2 menu items:

my_menu = Menu(root, tearoff=False)
my_menu.add_command(label="Show details", command=whatever)
my_menu.add_command(label="Delete me", command=something)

Now I want to add an if statement to check if the menu item: Delete me exists in menu or not. If exists, delete that menu item (like the following code snippet, just for demonstration)

if... :                                  #if statement to check if menu item "Delete me" exists
    my_menu.delete("Delete me")          #delete the menu item
else:
    pass

Solution

  • There are a lot of ways this is possible but the most dynamic way would be to get the index of the last item, and loop till the last index number and then do the checking:

    from tkinter import *
    
    root = Tk()
    
    def whatever():
        for i in range(my_menu.index('end')+1):
            if my_menu.entrycget(i,'label') == 'Delete me': # Delete if any has 'Delete me' as its label
                my_menu.delete("Delete me")
    
    my_menu = Menu(root, tearoff=False)
    my_menu.add_command(label='Show details', command=whatever)
    my_menu.add_command(label='Delete me')
    root.config(menu=my_menu)
    
    root.mainloop()