Python Check button Widget

Check buttons, also known as check boxes are useful for the user to select one or more options from available group of options.Check buttons are displayed in the form of square shaped boxes. When a check button is selected, a tick mark is displayed on the button.We can create check buttons using the Checkbutton class as:

c1 = Checkbutton(f, bg='yellow', fg= 'green', font=('Georgia', 20, 'underline'), text='Java', variable= var1, command=display)

Here, 'c1' is the object of Checkbutton class that represents a check button.'f' indicates frame for which the check button becomes a child. 'bg' and 'fg' represent the back ground and fore ground colors used for check button.'font' represents the font name, size and style.'text' represents the text to be displayed after the check button. The option variable represents an object of IntVar() class.'command' represents the method to be called when the user clicks the check button.

The class 'IntVar' is useful to know the state of the check button, whether it is clicked or not.The IntVar class object can be created as:

var1 = IntVar()

When the check button is clicked or selected, the value of 'var1' will be 1, otherwise its value will be 0.To retrieve the value from 'var1', we should use the get() method, as:

x = var1.get()# x value can be 1 or 0

Python Check Button Example

A Python program to create 3 check buttons and know which options are selected by the user

from tkinter import * 
class Mycheck: 
   def __init__(self, root): 
      self.f = Frame(root, height=350, width=500) 
      self.var1 = IntVar() 
      self.var2 = IntVar() 
      self.var3 = IntVar() 
      self.c1 = Checkbutton(self.f, bg='yellow', fg= 'green', font=('Georgia', 20, 'underline'), text='Java', variable= self.var1, command=self.display) 
      self.c2 = Checkbutton(self.f, text='Python', variable= self.var2,command=self.display) 
      self.c3 = Checkbutton(self.f, text='.NET', variable= self.var3, command=self.display) 
#attach check boxes to the frame, y=100), y=100), y=100)
   def display(self): 
      x = self.var1.get() 
      y = self.var2.get() 
      z = self.var3.get() 
      str = '' 
#catch user choice 
      if x==1: 
         str += 'Java ' 
      if y==1: 
         str+= 'Python ' 
      if z==1: 
         str+= '.NET ' 
      lbl = Label(text=str, fg='blue').place(x=50, y=150, width=200, height=20)  
root = Tk() 
#create an object to MyButtons class 
mb = Mycheck(root) 
#the root window handles the mouse click event