Tuesday 22 January 2008

Python Tkinter-Checkbutton

Cited from: http://effbot.org/tkinterbook/checkbutton.htm

To use a Checkbutton, you must create a Tkinter variable. To inspect the button state, query the variable.

from Tkinter import *

master = Tk()

var = IntVar()

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

mainloop()

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()

Example:

from Tkinter import *

def cb1():
print 'use c.var.get() to check the checkbutton value'

master=Tk()
v = IntVar()
c = Checkbutton(master, text="Color Image", variable=v, command=cb1)
c.var=v
c.pack()
master.mainloop()

No comments:

My photo
London, United Kingdom
twitter.com/zhengxin

Facebook & Twitter