[Tutor] Determinw Tkinter checkbox state, was Re: question

Peter Otten __peter__ at web.de
Thu Jan 13 09:30:14 CET 2011


Stinson, Wynn A Civ USAF AFMC 556 SMXS/MXDED wrote:

[In the future please take the time to choose a meaningful subject]

> Can someone give me some sample code to use to determine if a checkbox
> has been selected using Tkinter? thanks

Method 1: check the state of the underlying variable:

import Tkinter as tk

root = tk.Tk()

var = tk.IntVar()
cb = tk.Checkbutton(root, text="the lights are on", variable=var)
cb.pack()

def showstate():
    if var.get():
        print "the lights are on"
    else:
        print "the lights are off"

button = tk.Button(root, text="show state", command=showstate)
button.pack()

root.mainloop()

Method 2: trigger a function when the underlying variable changes

import Tkinter as tk

root = tk.Tk()

var = tk.IntVar()
cb = tk.Checkbutton(root, text="the lights are on", variable=var)
cb.pack()

def showstate(*args):
    if var.get():
        print "the lights are on"
    else:
        print "the lights are off"

var.trace_variable("w", showstate)
root.mainloop()




More information about the Tutor mailing list