Python - GUI Programming - Radio Button Widget
The Radiobutton widget is a GUI component used to select one option from a group of options. The radio button widget is used when the user needs to choose one option from a group of options. When the user selects one option, all other options are automatically deselected. The Radiobutton widget is used in conjunction with the variable class to associate the selected option with a variable.
Creating a Radio Button in Python:
To create a Radiobutton widget, we first need to import the Tkinter module. We then create an instance of the Radiobutton class, specifying the parent widget, text, variable, and value of the button.
radiobutton = Radiobutton(parent_widget, text=text, variable=variable_name, value=value)
In the above syntax:
- parent_widget: The parent widget where the radiobutton will be placed
- text: The label to be displayed next to the radiobutton
- variable: The variable to associate with the radiobutton
- value: The value to assign to the variable when this radiobutton is selected
Let's create a simple GUI application that uses a Radiobutton widget to select a favorite color.
from tkinter import *
class App(Frame):
def __init__(self, master=None):
super().__init__(master)
self.pack()
self.create_widgets()
def create_widgets(self):
self.favorite_color = StringVar()
self.favorite_color.set(None)
colors = [("Red", "red"), ("Green", "green"), ("Blue", "blue")]
for text, color in colors:
Radiobutton(self, text=text, variable=self.favorite_color, value=color).pack(anchor=W)
button = Button(self, text="Submit", command=self.submit)
button.pack(side=BOTTOM)
def submit(self):
print("Favorite color: ", self.favorite_color.get())
root = Tk()
app = App(master=root)
app.mainloop()
In the above program, we created a class App that inherits from Frame class. The constructor of the App class creates an instance of StringVar, which is used to store the selected color. We set the initial value to None, which means no option is selected.
Next, we create a list of tuples containing the text to display next to each radiobutton and the value to assign to the variable when this radiobutton is selected.
We then create a Radiobutton widget for each option in the list, passing in the parent widget, text, variable, and value.
Finally, we create a button widget to submit the selection and call the submit method to print the selected value.