Title: Use radio buttons in a menu with Python and tkinter
This is surprisingly easy once you figure it out. The program creates a variable to hold the option button selection and then adds radio buttons that use that variable to the menu.
The following code shows how the program creates the radio button menu items.
# Build the Scale menu.
self.scale_menu = tk.Menu(self.menu_bar, tearoff=False)
self.menu_bar.add_cascade(label='Scale', menu=self.scale_menu)
self.menu_bar.entryconfig('Scale')
self.selected_scale = tk.DoubleVar(value=1)
scales = [3, 2, 1, 0.5, 0.25, 0.1]
for scale in scales:
text = f'{scale:.0%}'
self.scale_menu.add_radiobutton(label=text,
variable=self.selected_scale, value=scale,
command=self.set_scale)
This code first creates the Scale menu. It then creates a DoubleVar to hold the selected scale. The variable's initial value is 1 to represent a 100% scale.
Next, the code creates a list of the scales that it will display on the Scale menu and loops through them. For each scale, the code converts the scale into a string of the form 25%. It uses the scale value and the text to add a radio button to the Scale menu. The button's variable property refers to the DoubleVar so, when you select an option, its value is placed in that variable.
When you select one of the radio buttons, the following code executes.
def set_scale(self):
print(self.selected_scale.get())
This code just displays the scale variable's value.
That's all there is to it! The radio buttons automatically ensure that the selected button is checked and the others are not.
Download the example to see additional details.
|