Radiobutton Tkinter

Radiobutton in Tkinter module is used as an option button. Radiobutton allows the user to choose one in many options. Each group of Radiobutton has to be associated with the same variable and value of a variable can change after a mouse click on the Radio button. You need to set the value for every radio button with a different value. Below example shows you how to create a radio button in the Tkinter python application.

from tkinter import *
win=Tk()
win.title("CoderMantra Tutorial")
win.geometry('200x200')

var=IntVar()
l1=Label(win,text="How do you want to pay")
l1.grid(row=0,column=0)
r1=Radiobutton(win,text="Cash",value=1,variable=var)
r1.grid(row=1,column=0)
r2=Radiobutton(win,text="Card",value=2,variable=var)
r2.grid(row=2,column=0)

win.mainloop()

intvar() – It is known as control variable, it keep the value and updated when changes reflect during programming. The get() and set() method is used to retrieve and set the value.

Get Radio Button Value (get selected radio)

To get the value of the selected radio button, we will use the intvar() method to create a variable and get() method to access the value.

from tkinter import *
def func():
	if var.get()==1:
		lbl.configure(text="Pay By Cash")
	elif var.get()==2:
		lbl.configure(text="Pay By Card")
	else:
		lbl.configure(text="Select your Option")

win=Tk()
win.title("CoderMantra Tutorial")
win.geometry('200x200')

var=IntVar()
l1=Label(win,text="How do you want to pay")
l1.grid(row=0,column=0)
r1=Radiobutton(win,text="Cash",value=1,variable=var)
r1.grid(row=1,column=0)
r2=Radiobutton(win,text="Card",value=2,variable=var)
r2.grid(row=2,column=0)

b=Button(win,text="Click Here",command=func)
b.grid(row=3,column=0)
lbl=Label(win,text="")
lbl.grid(row=4,column=0)
win.mainloop() 

We can create different small App like quiz application, restaurant billing system and many more using radio button widget.