简体   繁体   English

如何检查 Python Tkinter 中是否存在菜单项

[英]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:在 python tkinter我有以下代码用于创建只有 2 个Menu项的菜单:

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语句来检查菜单项:删除我是否存在于菜单中。 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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM