Update label of tkinter menubar item?

kiri picture kiri · Dec 4, 2013 · Viewed 7.5k times · Source

Is it possible to change the label of an item in a menu with tkinter?

In the following example, I'd like to change it from "An example item" (in the "File" menu) to a different value.

from tkinter import *

root = Tk()
menu_bar = Menu(root)

file_menu = Menu(menu_bar, tearoff=False)
file_menu.add_command(label="An example item", command=lambda: print('clicked!'))
menu_bar.add_cascade(label="File", menu=file_menu)

root.config(menu=menu_bar)
root.mainloop()

Answer

kiri picture kiri · Dec 4, 2013

I found the solution myself in the Tcl manpages:

Use the entryconfigure() method like so, which changes the value after it has been clicked:

The first parameter 1 has to be the index of the item you want to change, starting from 1.

from tkinter import *

root = Tk()
menu_bar = Menu(root)

def clicked(menu):
    menu.entryconfigure(1, label="Clicked!")

file_menu = Menu(menu_bar, tearoff=False)
file_menu.add_command(label="An example item", command=lambda: clicked(file_menu))
menu_bar.add_cascade(label="File", menu=file_menu)

root.config(menu=menu_bar)
root.mainloop()