So with the Checkbutton widget, instead of using an event handler, you link the widget to a
control variable. The text parameter in the Checkbutton object defines the text that appears next
to the check box in the window.
To retrieve the status of the Checkbutton widget in your code, you need to use the get() method
for the control variable, like this:
Click here to view code image
option1 = self.varCheck1.get()
if (option1):
print('The checkbutton was selected')
else:
print('The checkbutton was not selected')
Listing 18.5 shows the script1805.py program, which demonstrates how to use a
Checkbutton object in a program.
LISTING 18.5 The script1805.py Code
Click here to view code image
#!/usr/bin/python3
from tkinter import *
class Application(Frame):
"""Build the basic window frame template"""
def __init__(self, master):
super(Application, self).__init__(master)
self.grid()
self.varSausage = IntVar()
self.varPepp = IntVar()
self.create_widgets()
def create_widgets(self):
self.label1 = Label(self, text='What do you want on your pizza?')
self.label1.grid(row=0)
self.check1 = Checkbutton(self, text='Sausage', variable =
self.varSausage)
self.check2 = Checkbutton(self, text='Pepperoni', variable =
self.varPepp)
self.check1.grid(row=1)
self.check2.grid(row=2)
self.button1 = Button(self, text='Order', command=self.display)
self.button1.grid(row=3)
def display(self):
"""Event handler for the button, displays selections"""
if (self.varSausage.get()):
print('You want sausage')
if (self.varPepp.get()):
print('You want pepperoni')
if ( not self.varSausage.get() and not self.varPepp.get()):
print("You don't want anything on your pizza?")
print('----------')
root = Tk()
root.title('Test Checkbutton events')
root.geometry('300x100')