Python: Radio buttons in Tkinter
In this blog, we are going to see how we can use the Tkinter library in Python to create radio buttons in a GUI.
Radio buttons are used to provide options to the user through a GUI where usually only one option is to be selected.
Many forms and data entry software use this feature to have the input from the user.
many GUIs being used in creating quiz formats also use radio buttons for multiple-choice questions where answers to be selected are provided to the user through them.
Syntax:
w = Radiobutton ( master, option, … )
Tkinter Radio button code in Python
#Import library from tkinter import * #Define Function def sel(): select = "Option selected by you is the " + str(var.get()) label.config(text = select) #Define Buttons in GUI root = Tk() var = IntVar() #Button One R1 = Radiobutton(root, text="First Choice", variable=var, value=1, command=sel) R1.pack( anchor = W ) #Button Two R2 = Radiobutton(root, text="Second Choice", variable=var, value=2, command=sel) R2.pack( anchor = W ) #Button Three R3 = Radiobutton(root, text="Third Choice", variable=var, value=3, command=sel) R3.pack( anchor = W) #Labels label = Label(root) label.pack() root.mainloop()
Output
Explanation
The master attribute represents the parent window whereas the options attribute can be used to add key-value pairs separated by commas in the syntax for Radio Buttons.
Here each button symbolizes a single value.
The options available within the library are a variety of attributes like active background, bitmap, cursor, font, height, etc.
There are more than 25 options available here.
There are a few methods also available to be used along with the button attributes.
They can be select(), deselect(), flash(), invoke().
These methods make the task of using Radio Buttons easier and convenient.
Also read: How to show a GIF animation image in Tkinter – Python
Leave a Reply