tkinter
  1. tkinter-radiobutton

Radiobutton

In this article, we will discuss the Radiobutton widget, which is part of the List and Selection Widgets in Tkinter. The Radiobutton widget is a group of buttons in which only one button can be selected at a time.

Syntax

The basic syntax for creating a Radiobutton widget is as follows:

rb = Radiobutton(parent, text="Option 1", variable=var, value=1)
rb.pack()

In this syntax, the parent parameter represents the parent window or frame in which the Radiobutton needs to be placed. The text parameter represents the label that needs to be displayed next to the button. The variable parameter represents the Tkinter variable that is used to store the selected button's value. Lastly, the value parameter represents the value associated with the button.

Example

Let's look at an example that creates three Radiobutton widgets with options Option 1, Option 2, and Option 3:

from tkinter import *

root = Tk()
root.geometry("200x100")

# create a variable to store the selected option
selected_option = IntVar()

# create three Radiobutton widgets
rb1 = Radiobutton(root, text="Option 1", variable=selected_option, value=1)
rb1.pack()

rb2 = Radiobutton(root, text="Option 2", variable=selected_option, value=2)
rb2.pack()

rb3 = Radiobutton(root, text="Option 3", variable=selected_option, value=3)
rb3.pack()

root.mainloop()

When you run this code, you will see three Radiobutton widgets with options Option 1, Option 2, and Option 3.

Output

The output of the above code will be a window with three Radiobutton widgets with options Option 1, Option 2, and Option 3. You can select only one button at a time.

Explanation

The Radiobutton widget is used to create a group of buttons in which only one button can be selected at a time. When a button is selected, the associated value is stored in a Tkinter variable that is passed as a parameter to the Radiobutton widget.

Use

The Radiobutton widget is useful when you want to provide the user with a group of options to choose from, but only one can be selected at a time.

Important Points

  • The Radiobutton widget is part of the List and Selection Widgets in Tkinter.
  • Only one Radiobutton button can be selected at a time.
  • The variable parameter passed to the Radiobutton widget should be an instance of the Tkinter IntVar, DoubleVar, or StringVar class.
  • Each Radiobutton button should have a unique value.

Summary

The Radiobutton widget in Tkinter is used to create a group of buttons in which only one button can be selected at a time. We learned about its syntax, examples, output, explanation, use, and important points in this article.

Published on: