How to Update the label of the Tkinter menubar item?

TkinterServer Side ProgrammingProgramming

A Menubar contains a set of Menu Item in which each Menu Item is defined for different functionalities or operations. Let us suppose that we want to update the label of Menu Bar Items, then we can use entryconfigure(item_number, options..) method in a callback. To update the Menu Items in the Menu Bar, we can add label in the above method.

Example

Let us create an application with a list of Menu Items in the Menu Bar. When we will click a Particular Item, it will change the text in it.

#Import the required Library
from tkinter import *
#Create an Instance of tkinter frame
win= Tk()

#Set the geometry of the window
win.geometry("750x250")

#Create a Menu Bar
menu_bar = Menu(win)

#Define a function to change the Menu Label
def clicked(menu):
   menu.entryconfigure(1, label="You have Clicked!")
   Label(win, text= "You have Selected a Menu", font= (None,14)).pack(pady=20)

#Create a Menu Items
file_menu = Menu(menu_bar, tearoff=False)
file_menu.add_command(label="Click Me", command=lambda:
clicked(file_menu))

#Create a Menu Bar
menu_bar.add_cascade(label="File", menu=file_menu)
win.config(menu=menu_bar)
win.mainloop()

Output

Running the above code will display a window that contains a Menu Bar. When we click the Menu Item, it will change its label quickly.

When we click File → Click Me, it will change its label text and display a message on the screen.

raja
Published on 03-May-2021 11:29:35
Advertisements