pythonware.com products ::: library ::: search ::: daily Python-URL!
   

Patterns

Back   Next   

 Patterns

(Also see the Button patterns).

To use a Checkbutton, you must create a Tkinter variable:

    var = IntVar()
    c = Checkbutton(master, text="Expand", variable=var)

By default, the variable is set to 1 if the button is selected, and 0 otherwise. You can change these values using the onvalue and offvalue options. The variable doesn't have to be an integer variable:

    var = StringVar()
    c = Checkbutton(
        master, text="Color image", variable=var,
        onvalue="RGB", offvalue="L"
        )

If you need to keep track of both the variable and the widget, you can simplify your code somewhat by attaching the variable to the widget reference object.

    v = IntVar()
    c = Checkbutton(master, text="Don't show this again", variable=v)
    c.var = v

If your Tkinter code is already placed in a class (as it should be), it is probably cleaner to store the variable in an attribute, and use a bound method as callback:

    def __init__(self, master):
        self.var = IntVar()
        c = Checkbutton(master, text="Enable Tab",
                        variable=self.var, command=self.cb)
        c.pack()

    def cb(self, event):
        print "variable is", self.var.get()

Back   Next