Python Forum

Full Version: Is there a way to determine if a radio button has been selected?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello, as Im now to Python any help is appreciated
My goal is to determine if a radio button has been selected, to help troubleshoot I have created a short if statement to print out the results on weather it has or has not.
I have viewed this forum for other similar questions but haven't seem to quite get there
I have posted a snippet of the relevant code.
My question is is there a way to determine if a radio button has been selected and how would I incorporate it into the following if statement.
thanks

 #Radio Buttons Menu options
 #Button to enter player name
 self.button_selected = IntVar()
 self.button_selected.set(0)

#Radio button to add player name  
self.menu_button1 = Radiobutton(self, text = "Add player names",
           variable = self.button_selected, value = 0)       
self.menu_button1.grid(row = 3, column = 0, sticky="W")

#Radio button to view all scores
            self.menu_button2 = Radiobutton(self, text = "View all player scores",
                        variable = self.button_selected, value = 1)       
self.menu_button2.grid(row = 4, column = 0, sticky="W")

#if statment or troubleshooting
if Radiobutton.value ==   ???????  #not sure where to go here????
     print("radio button IS selected")
else:
     print("radio button IS NOT selected")
I think that you're going to need to use the command= option to execute a function for each button.

Example:

def add_player_names():
    print("Add player names.")


def view_player_scores():
    print("View player scores.")


# Radio button to add player name
menu_button1 = Radiobutton(text="Add player names",
                           variable=button_selected, value=0, command=add_player_names)
menu_button1.grid(row=3, column=0, sticky="W")

# Radio button to view all scores
menu_button2 = Radiobutton(text="View all player scores",
                           variable=button_selected, value=1, command=view_player_scores)
menu_button2.grid(row=4, column=0, sticky="W")
If you have a snippet of code try and make it as complete and runnable as you can so others don't have to.
The following has a function on_button_selected that gets the value of the IntVar that is tied to both RadionButtons
I called the method at the end of the __init__ to show the value at the beginning and it will be called when the radio buttons are clicked.
import tkinter as tk


class RadioFrame(tk.Frame):
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        self.pack()
        # Radio Buttons Menu options
        # Button to enter player name
        self.button_selected = tk.IntVar()
        self.button_selected.set(0)

        # Radio button to add player name
        self.menu_button1 = tk.Radiobutton(
            self, text="Add player names", variable=self.button_selected, value=0
        )
        self.menu_button1.grid(row=3, column=0, sticky="W")

        # Radio button to view all scores
        self.menu_button2 = tk.Radiobutton(
            self, text="View all player scores", variable=self.button_selected, value=1
        )
        self.menu_button2.grid(row=4, column=0, sticky="W")
        self.button_selected.trace_add("write", self.on_button_selected)
        self.on_button_selected()

    def on_button_selected(self, *args):
        # #if statment or troubleshooting
        button_selected_value = self.button_selected.get()
        if button_selected_value == 0:
            print("radio button menu_button1 is selected")
        elif button_selected_value == 1:
            print("radio button menu_button2 is selected")


def main():
    app = tk.Tk()
    radio_frame = RadioFrame(app)
    app.mainloop()


if __name__ == "__main__":
    main()
The radio button variable contains the value associated with the selected button. Use variable.get() to get the value associated with the selected button. You can use variable.set(value) to set the variable value which also changes the selected radio button.
import tkinter as tk


class Window(tk.Tk):
    def __init__(self):
        super().__init__()
        self.selected = tk.IntVar(self, 0)
        self.radio_buttons = [
            tk.Radiobutton(self, text=f"Button {i}", variable=self.selected, value=i)
            for i in range(5)
        ]
        for button in self.radio_buttons:
            button.pack(padx=10, pady=(10, 0))
        button = tk.Button(self, text="Push Me", command=self.push_me)
        button.pack(padx=10, pady=10)

    def push_me(self):
        value = self.selected.get()
        print(value)
        self.selected.set((value + 1) % len(self.radio_buttons))


Window().mainloop()
If you want to execute a command when the radio buttons are pressed, you have two choices (or more). You can connect a command to the button as mentioned in rob101's post. Be aware that the command is only called when you click on the buttons. Changing the radio button variable does not execute the function.
class Window(tk.Tk):
    def __init__(self):
        super().__init__()
        self.selected = tk.IntVar(self, 0)
        self.radio_buttons = [
            tk.Radiobutton(
                self,
                text=f"Button {i}",
                variable=self.selected,
                value=i,
                command=self.report,
            )
            for i in range(5)
        ]
        for button in self.radio_buttons:
            button.pack(padx=10, pady=(10, 0))
        button = tk.Button(self, text="Push Me", command=self.push_me)
        button.pack(padx=10, pady=10)

    def report(self):
        print(self.selected.get())

    def push_me(self):
        value = self.selected.get()
        self.selected.set((value + 1) % len(self.radio_buttons))


Window().mainloop()
Another option is to add a trace to the variable. This calls a function each time the variable value changes.
class Window(tk.Tk):
    def __init__(self):
        super().__init__()
        self.selected = tk.IntVar(self, 0)
        self.selected.trace_add("write", self.report)
        self.radio_buttons = [
            tk.Radiobutton(self, text=f"Button {i}", variable=self.selected, value=i)
            for i in range(5)
        ]
        for button in self.radio_buttons:
            button.pack(padx=10, pady=(10, 0))
        button = tk.Button(self, text="Push Me", command=self.push_me)
        button.pack(padx=10, pady=10)

    def report(self, *_):
        print(self.selected.get())

    def push_me(self):
        value = self.selected.get()
        self.selected.set((value + 1) % len(self.radio_buttons))


Window().mainloop()
Thank you for your direction, it was very helpful
(Jan-15-2023, 04:11 PM)TWB Wrote: [ -> ]Hello, as Im now to Python any help is appreciated
My goal is to determine if a radio button has been selected, to help troubleshoot I have created a short if statement to print out the results on weather it has or has not.
I have viewed this forum for other similar questions but haven't seem to quite get there
I have posted a snippet of the relevant code.
My question is is there a way to determine if a radio button has been selected and how would I incorporate it into the following if statement.
thanks

 #Radio Buttons Menu options
 #Button to enter player name
 self.button_selected = IntVar()
 self.button_selected.set(0)

#Radio button to add player name  
self.menu_button1 = Radiobutton(self, text = "Add player names",
           variable = self.button_selected, value = 0)       
self.menu_button1.grid(row = 3, column = 0, sticky="W")

#Radio button to view all scores
            self.menu_button2 = Radiobutton(self, text = "View all player scores",
                        variable = self.button_selected, value = 1)       
self.menu_button2.grid(row = 4, column = 0, sticky="W")

#if statment or troubleshooting
if Radiobutton.value ==   ???????  #not sure where to go here????
     print("radio button IS selected")
else:
     print("radio button IS NOT selected")

You can use the IntVar associated with the Radiobutton to determine if it has been selected.

if self.button_selected.get() == 0:
print("radio button IS selected")
else:
print("radio button IS NOT selected")