Home > Software design >  Python Tkinter: radio buttons are toggled globally in all menus instead of one
Python Tkinter: radio buttons are toggled globally in all menus instead of one

Time:10-27

How to achieve that the radio button switches in each menu separately and not globally in all? The moment I switch the radio button in the Family menu, for example, it is unchecked in the Size menu and vice versa.

I also want to set a default checked radio button for each menu, but I don't know how to do that.

This is my code:

#!/usr/bin/env python3


from tkinter import *


root = Tk     ()
root.geometry ("500x500")
root.title    ("Program")


menu_bar = Menu (
    master = root
)
root.config (
    menu = menu_bar
)


fami_menu = Menu (
    master = menu_bar,
    tearoff = False,
)
fami_menu.add_radiobutton (
    label = "Sans Serif",
)
fami_menu.add_radiobutton (
    label = "Serif",
)
menu_bar.add_cascade (
    label = "Family",
    menu = fami_menu,
)


size_menu = Menu (
    master = menu_bar,
    tearoff = False,
)
size_menu.add_radiobutton (
    label = "11",
)
size_menu.add_radiobutton (
    label = "12",
)
menu_bar.add_cascade (
    label = "Size",
    menu = size_menu,
)


root.mainloop ()

CodePudding user response:

You have to create a variable (Stringvar) for each of the menu and specify it with kwarg variable while instanciating your radiobuttons. That way they will be set independently:

from tkinter import *

root = Tk     ()
root.geometry ("500x500")
root.title    ("Program")

menu_bar = Menu (
    master = root
)
root.config (
    menu = menu_bar
)


fami_menu = Menu (
    master = menu_bar,
    tearoff = False,
)

menu_bar.add_cascade (
    label = "Family",
    menu = fami_menu,
)
fami_selected = StringVar()
fami_menu.add_radiobutton (
    label = "Sans Serif",
    variable = fami_selected
)
fami_menu.add_radiobutton (
    label = "Serif",
    variable = fami_selected
)


size_menu = Menu (
    master = menu_bar,
    tearoff = False,
)
menu_bar.add_cascade (
    label = "Size",
    menu = size_menu,
)
size_selected = StringVar()
size_menu.add_radiobutton (
    label = "11",
    variable = size_selected
)
size_menu.add_radiobutton (
    label = "12",
    variable = size_selected
)

root.mainloop ()

CodePudding user response:

You'll want to add a variable for each group of radio buttons, where variable is a StringVar(), IntVar(), or similar. You can set the default radio selection by setting this variable to a "value" matching one of your buttons.

# this variable will store the value of the selected button
fami_var = tk.StringVar()  # I'm using a string variable here

fami_menu.add_radiobutton (
    label="Sans Serif",
    value='Sans',  # this can be whatever string you want
    variable=fami_var,
)
fami_menu.add_radiobutton (
    label="Serif",
    value='Serif',
    variable=fami_var,
)
fami_var.set('Sans')  # set the default selection

You'll want to do a similar thing with size_menu and a separate StringVar()

  • Related