Making Menu options with Checkbutton in Tkinter?

TkinterServer Side ProgrammingProgramming

The Menu Bar in Tkinter can be created by initializing Menu (parent) instances in the application. We can add checkbuttons in place of add_command to extend the feature of Menu Bar in any application.

To add the menu items using the add_checkbutton(label, options) method, we first initialize a Menu Bar. Once the MenuBar is defined, we can give the value of menu items by using Checkbuttons. The CheckButtons can be used to add the list of Menu Items or options. Checkbuttons are nothing but the Boolean widget, which validates a particular value by making it True or False. To mark the status of checkbuttons in the menu items, we can use onvalue and offvalue.

Example

#Import the required Libraries
from tkinter import *
#Create an instance of Tkinter frame
win = Tk()
#Set the geometry of Tkinter Frame
win.geometry("750x250")

#Initialize a Menu Bar
menubar = Menu(win)

#Add Menu Items in the MenuBar
menu_items = Menu(menubar)
menu_items.add_checkbutton(label="C++", onvalue=1, offvalue=0)
menu_items.add_checkbutton(label="Java", onvalue=1, offvalue=0)
menu_items.add_checkbutton(label="Python", onvalue=1, offvalue=0)

# Add the Viwable Menu to the MenuBar
menubar.add_cascade(label='File', menu=menu_items)
win.config(menu=menubar)

win.mainloop()

Output

Run the above code to display a Menu Bar which is having the Menu Items of CheckButtons.

When we select an item in the Menu, it will mark the item on/off.

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