Page 367 -
P. 367
flip it off
Working with checkboxes in tkinter
The tkinter Checkbutton needs three things: an IntVar to hold its
current value, an event-handler function to run when it’s ticked, and a
descriptive label to say what it does. Take a look at this example code:
Create an “IntVar” to hold a value that
flipper = IntVar() is either 1 or 0, depending on whether
The “flip_it()" the checkbox is ticked.
function is the
Checkbutton's
event handler. def flip_it():
if flipper.get() == 1:
print("Cool. I'm all ON, man!")
else:
print("Phooey. I'm OFF.")
The Checkbutton is Checkbutton(app, variable = flipper,
associated with the
“IntVar”, links to the command = flip_it,
event handler, and has text = "Flip it?").pack()
a descriptive label, too.
Cool. I‛m all
ON, man!
Using the get() method
If you look closely at the code for the flip_it()
event handler, you’ll notice that the message displayed
on screen is controlled by whatever value is returned
from the call to flipper.get(). The get()
method is part of every IntVar object, and it lets Phooey.
you easily determine, in this case, the current value I‛m OFF.
associated with the flipper variable.
But, what sets the value?
The Checkbutton automatically sets the value of
flipper as a result of the click on the checkbox.
Tick the box and the value is set to 1. Untick the box
and the value is set to 0.
332 Chapter 9