Python tkinter Radiobutton

A radio button is similar to a check button, but it is useful to select only one option from a group of available options.A radio button is displayed in the form of round shaped button.

tkinter radiobutton

The user cannot select more than one option in case of radio buttons.When a radio button is selected, there appears a dot in the radio button.We can create a radio button as an object of the Radiobutton class as:

Syntax

CopiedCopy Code
r1 = Radiobutton(f, bg='yellow', fg= 'green', font=('Georgia', 20, 'underline'), text='Male', variable= var, value=1, command=display)

The option 'text' represents the string to be displayed after the radio button.'variable' represents the object of IntVar class.'value' represents a value that is set to this object when the radio button is clicked.The object of IntVar class can be created as:

tkinter radiobutton get value

CopiedCopy Code
var = IntVar()

When the user clicks the radio button, the value of this 'var' is set to the value given in 'value' option, i.e. 1.It means 'var' will become 1 if the radio button 'r1' is clicked by the user.In this way, it is possible to know which button is clicked by the user.

tkinter Radiobutton selected example

A Python program to create radio buttons and know which button is selected by the user

CopiedCopy Code

from tkinter import * 
class Myradio: 
   def __init__(self, root): 
      self.f = Frame(root, height=350, width=500) 
      self.f.propagate(0) 
      self.f.pack() 
      self.var = IntVar() 
      self.r1 = Radiobutton(self.f, bg='yellow', fg= 'green', font=('Georgia', 20, 'underline'), text='Male', variable= self.var, value=1, command=self.display) 
      self.r2 = Radiobutton(self.f, text='Female', variable= self.var,value=2, command=self.display) 
      self.r1.place(x=50, y=100) 
      self.r2.place(x=200, y=100) 
   def display(self): 
      x = self.var.get() 
      str = ' ' 
      if x==1: 
          str += 'You selected: Male ' 
      if x==2: 
         str+= 'You selected: Female ' 
      lbl = Label(text=str, fg='blue').place(x=50, y=150, width=200, height=20) 
root = Tk() 
mb = Myradio(root) 
root.mainloop()