1

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
Delrius Euphoria
  • 14,910
  • 3
  • 15
  • 46

2 Answers2

1

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()
Delrius Euphoria
  • 14,910
  • 3
  • 15
  • 46
  • Solution 3 is what I need, however this partially solves my problem. It would be more efficient to find how many menu items existed, instead of just putting a random number (such as 10). Because once it goes out of index, it will create errors. – Kleiton Kurti Jan 17 '21 at 16:22
0
def menu_has_item(menu, label):
    try:
        menu.index(label)
        return True
    except TclError:
        return False


root = Tk()

details = "Show details"
delete = "Delete me"

my_menu = Menu(root, tearoff=False)
my_menu.add_command(label=details, command=whatever)
my_menu.add_command(label=delete, command=whatever)

root.config(menu=my_menu)

print(menu_has_item(my_menu, 'Not in'))
print(menu_has_item(my_menu, details))

This returns the following:

False
True
BoobyTrap
  • 967
  • 7
  • 18