1

在 pythontkinter上,我有以下代码用于创建Menu只有 2 个菜单项的 a:

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

现在我想添加一个if语句来检查菜单项:删除我是否存在于菜单中。如果存在,则删除该菜单项(如以下代码片段,仅用于演示)

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

2 回答 2

1

有很多方法可以做到这一点,但最动态的方法是获取最后一项的索引,然后循环到最后一个索引号,然后进行检查:

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()
于 2021-01-17T16:11:42.977 回答
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))

这将返回以下内容:

False
True
于 2021-01-17T16:23:30.990 回答