Tkinter - Radio Buttons in Python

This is an example tkinter gui which uses radio buttons to allow the user to select from predefined options.
import tkinter

def printVariable(event=0):
    #This function prints the option selected, from the index
    #event is set to zero as default
    print ("Option " + str(var.get() + 1))
    
#defines a window
window = tkinter.Tk()

#Sets window title
window.title("Radiobox Example")

#create a inteer varaible
var = tkinter.IntVar()

#Set a default value
var.set(3)

#List of options 
options = ["Option 1",
           "Option 2",
           "Option 3",
           "Option 4"]

#Creates a label prompting for selection
lbl = tkinter.Label(window, text = "Make make a selection")
#pack the label
lbl.pack()

#interates through the list and creates a radio button for each option
#enumberate generates an index for each item, that we can assign to the value of each button
for opt, option in enumerate(options):
    rad = tkinter.Radiobutton(window, text=option, padx = 10, variable=var, value=opt)
    rad.pack()

#button to confirm selection
btn = tkinter.Button(window, text = " Select ", command=printVariable)
#pack the button
btn.pack()

#Return / Enter runs the fucntion the same as clicking the button
window.bind('<Return>', printVariable)

window.mainloop()
This generates this GUI window

On pressing the "Select" button or pressing return, the follwoing is printed.

Option 1






Related Sections

Python - Learn the python from the basics up. This fast track example code course will get you creating powerful python programs in no time.
Tkinter - Learn the key features of the tkinter to allow you to create user interfaces for your python programs.


Must Read Articles

Tkinter - Combo Box - This is a short example showing how to use combo boxes in a GUI.
Tkinter - Radio Buttons - A short example of how to create a GUI with radio buttons.
Tkinter _ Canvas - Canvas allows for a range of shapes to be plotted, such as circles, squares, lines and labels.
Tkinter - Pack vs Grid vs Place - tkinter provides flexibility in how the layout the widgets. 
Pickle - The pickle library allows a program to save data in a binary file.
Python - List Comprehension - Create powerful list comprehension expressions.
Python - Generators - Learn about generator statements.
Python - Data types - The learn about the key datatypes in the python language.