The Checkbutton and Radiobutton widgets

The Checkbutton and Radiobutton widgets allow a user to select an option by clicking to mark a box. A Checkbutton will allow the user to turn an option either on or off, whereas a Radiobutton is used to give the user a choice of one option from a group of multiple possibilities.

To get the values of each, a variable is passed to them via the variable keyword argument. With Radiobutton widgets, all possible options should be pointed to the same variable; then the user's chosen option can be obtained by querying this variable.

Let's have a look at the two in action:

import tkinter as tk

win = tk.Tk()

likes_python = tk.IntVar()
has_laptop = tk.IntVar()

c = tk.Checkbutton(win, variable=likes_python, text="Likes Python")
r1 = tk.Radiobutton(win, variable=has_laptop, text="Has Laptop", value=1)
r2 = tk.Radiobutton(win, variable=has_laptop, text="Does not have laptop", value=0)

We create two variables – one representing whether the user likes Python and one for if they own a laptop.

The likes_python variable is then bound to a Checkbutton instance, along with the text Likes Python.

The has_laptop variable is assigned to two Radiobutton instances. One represents the user having a laptop and is assigned the value 1. The other represents the user not having a laptop and is assigned the value 0.

When the Likes Python button is not checked, the IntVar it is bound to will have the value 0. When ticked, that will change to a 1. This is the default behavior of the Checkbutton widget and does not need to be changed.

Likewise, if the user selects that they do not have a laptop, the value of the has_laptop IntVar will be 0. If they instead select Has Laptop, its value will become 1.

We can now finish off this demo by displaying the information and packing our widgets.

label1 = tk.Label(win, textvar=likes_python)
label2 = tk.Label(win, textvar=has_laptop)


c.pack()
r1.pack()
r2.pack()
label1.pack()
label2.pack()

win.mainloop()

We create two Label widgets, which are bound to our IntVar objects. This allows us to see the values change as we check and uncheck the buttons. All widgets are then packed and our window begins its main loop.

Give this demo file a run and see the results. Try clicking options and watching the text at the bottom of the window change in response:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset