How to Create Radio Buttons with tkinter Library in Python


The following example will create a radio button for five sports items and a text label to display the user’s selection on the text label.
The Radiobutton control is used to create a radio button. In order for a group of radio buttons to perform the same function, you must set the variable property of the group of radio buttons to the same value, and the value of the value property is the value of each radio button.

The following are the properties of the Radiobutton control:

  • command: The function called when the user clicks this radio button.
  • variable: The variable to be updated when the user clicks this radio button.
  • width: The value to be stored in the variable when the user clicks this radio button.

The following are the methods of the Radiobutton control:

  • flash(): Interchanges the foreground and background colors to produce a flickering effect.
  • invoke(): Executes the function defined by the command property.
  • select (): Select this radio button, set the value of the variable to the value of the value attribute.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# radioButton.py

from tkinter import *

win = Tk()

#sport items
sports = ["Football", "Basketball", "Tennis", "Volleyball", "Baseball"]

# display user's choice
def showSelection():
    choice = "Your choice is: " + sports[var.get()]
    label.config(text = choice)

var = IntVar()
# set the layout of button
Radiobutton(win, text=sports[0], variable=var, value=0,command=showSelection).pack(anchor=W)
Radiobutton(win, text=sports[1], variable=var, value=1,command=showSelection).pack(anchor=W)
Radiobutton(win, text=sports[2], variable=var, value=2,command=showSelection).pack(anchor=W)
Radiobutton(win, text=sports[3], variable=var, value=3,command=showSelection).pack(anchor=W)
Radiobutton(win, text=sports[4], variable=var, value=4,command=showSelection).pack(anchor=W)

label = Label(win)
label.pack()

win.mainloop()

Output

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments