Radio Buttons in Tkinter (GUI Programming) – Python Tutorial

Radio Button: In Tkinter, Radio Button is the widget used in Python for performing one-of-many selections. Means when we have to perform operations, where we have to choose only one option out of multiple available options. Radio Button can contain images and text as well. We will use or associate Python Function with each radio button. These functions or methods are called automatically, when any specific radio button is chosen or checked.

python-video-tutorials

Radio Buttons are used commonly in user forms.

Syntax:

rbtn = Radiobutton(root, text="btn name", variable = "shared variable", 
                      value = "values of each button", options = values)

shared variable: A variable shared among all Radio Buttons
value: each and every radio button have different value else by-default more than one radio button will get selected.

radio-button

Let’s see some examples to understand the concept of Radio Buttons clearly

Example 1:

# Importing Tkinter module
from tkinter import *

root = Tk()
root.title("PythonLobby")

# Tkinter string variable it can store any string value
value1 = StringVar(root, "2")

rbtn1 = Radiobutton(root, text="Radio Button 1", variable = value1 , value="1")
rbtn1.pack()
rbtn2 = Radiobutton(root, text="Radio Button 2", variable = value1 , value="2")
rbtn2.pack()
rbtn3 = Radiobutton(root, text="Radio Button 3", variable = value1 , value="3")
rbtn3.pack()

root.geometry("250x200")
mainloop()

Output

radio-buttons-in-tkinter

Advanced method to create radio buttons using dictionary and loop

Example 2:

from tkinter import *

#root window
root = Tk() 

var = StringVar(root, "1")

# Dictionary to create multiple buttons 
val = {"Radio Button 1" : "1", "Radio Button 2" : "2", "Radio Button 3" : "3", }

# Loop used to create multiple Buttons
for (text, value) in val.items():
	btn = Radiobutton(root, text = text, variable = var, value = value).pack(pady=15)

root.geometry("175x175")
root.title("PythonLobby")
mainloop() 

Output:

radio-button-tkinter-python