Tkinter – Checkbutton Menu Items

Checkbutton Menu Items in Tkinter

In Tkinter, you can create menu items with checkbutton functionality using the add_checkbutton() method of the Menu class.

Checkbutton menu items allow users to select or deselect an option from the menu.

To add a checkbutton menu item to a menu in Tkinter, call add_checkbutton() method on the menu, and specify the values for label, variable, and command parameters.

add_checkbutton(label="Some text", variable=some_var, command=some_function)

In this tutorial, you will learn how to add a checkbutton menu item to a menu, with examples.

Steps to create Checkbutton Menu Item in Tkinter

Step 1

Define a function that can be used for the callback function of Checkbutton menu item.

def option_event():
    if option_1.get():
        print("Option selected")
    else:
        print("Option deselected")

Inside the callback function, we retrieve the state of the checkbutton from the option_1 variable using option_1.get(). Based on the state, we can perform the desired actions.

Please note that we create the variable option_1 later in step 3.

Step 2

Create a menu menu_1 in menu bar using Tk.Menu class.

menu_bar = tk.Menu(window)
menu_1 = tk.Menu(menu_bar, tearoff=False)

Step 3

Create a Tk boolean variable to store the state of the checkbutton menu item.

option_1 = tk.BooleanVar()

Step 4

Add checkbutton to the menu. Specify the label, variable, and command arguments.

menu_1.add_checkbutton(label="Option 1", variable=option_1, command=option_event)

Step 5

Cascade menu Menu1 to the menu bar, and configure the Tk window with the menu bar.

Example

In this example, we shall create a menu Menu1 in the menu bar. To this Menu1, we add a checkbutton menu item.

Program

import tkinter as tk

def option_event():
    if option_1.get():
        print("Option selected")
    else:
        print("Option deselected")

# Create the main window
window = tk.Tk()

# Create the menu bar
menu_bar = tk.Menu(window)

# Create the menu Menu1
menu_1 = tk.Menu(menu_bar, tearoff=False)

# Create a variable to store the state of the checkbutton
option_1 = tk.BooleanVar()

# Add items for Menu1
menu_1.add_checkbutton(label="Option 1", variable=option_1, command=option_event)

# Add the menu to the menu bar
menu_bar.add_cascade(label="Menu1", menu=menu_1)

# Attach the menu bar to the main window
window.config(menu=menu_bar)

# Start the Tkinter event loop
window.mainloop()

Output

Summary

In this Python Tkinter tutorial, we learned how to add checkbutton menu item to a menu, with examples.

Related Tutorials

Privacy Policy Terms of Use

SitemapContact Us