For a project, I want the options in a menu to change based off of the input from another menu. To do this, my original plan would be to delete all options from the menu and add new ones to it to correspond with the other menu; however, I've been having trouble deleting all of the options.
I've been looking around in menu tutorials and documentation for some kind of function or method that would return a list of options, so that I could find the length and loop through the indices to delete the options, but I've found nothing.
Some questions I have:
- Is there a way to get a list of options in a menu?
- Is there an easier way to delete all options from a menu?
CodePudding user response:
The delete
method can be given a range of items. You can pass 0
(zero) for the first item in the range, and the string "end"
or "last"
for the last item in order to delete all items on the menu.
Run the following example, open the menu and select "clear", then open the menu again and you'll see that all items have been deleted.
import tkinter as tk
import random
root = tk.Tk()
menubar = tk.Menu(root)
root.configure(menu=menubar)
options_menu = tk.Menu(menubar)
menubar.add_cascade(label="Options", menu=options_menu)
for i in range(random.randint(5, 10)):
options_menu.add_command(label=f"Option #{i 1}")
def clear_menu():
options_menu.delete(0, "end")
options_menu.add_separator()
options_menu.add_command(label="clear", command=clear_menu)
root.mainloop()
I've been looking around in menu tutorials and documentation for some kind of function or method that would return a list of options, so that I could find the length and loop through the indices to delete the options, but I've found nothing.
You can use the index
method to get the numerical index of an item. You can pass "end"
to get the index of the last item.
last_menu_item = option_menu.index("end")