Python Forum
[Tkinter] Is there a way to determine if a radio button has been selected?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tkinter] Is there a way to determine if a radio button has been selected?
#1
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")
Reply
#2
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")
Sig:
>>> import this

The UNIX philosophy: "Do one thing, and do it well."

"The danger of computers becoming like humans is not as great as the danger of humans becoming like computers." :~ Konrad Zuse

"Everything should be made as simple as possible, but not simpler." :~ Albert Einstein
Reply
#3
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()
Reply
#4
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()
Reply
#5
Thank you for your direction, it was very helpful
Reply
#6
(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")
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tkinter] Radio Buttons Working Bassackwards gw1500se 6 2,544 Dec-07-2021, 07:13 PM
Last Post: menator01
  [Tkinter] Grid the radio buttons Joni_Engr 6 5,281 Nov-24-2021, 07:20 PM
Last Post: menator01
  Radio butto to enable/disable combo box in Tkinter cybertooth 5 5,960 Oct-09-2021, 07:30 AM
Last Post: cybertooth
  problem with radio button crook79 3 4,036 Aug-12-2021, 02:30 PM
Last Post: deanhystad
  [Tkinter] I can't get information from a radio button aquerci 2 2,905 May-20-2020, 10:31 AM
Last Post: aquerci
  [PyQt] Avoid clicked event from button when button is not physically selected and clicked mart79 2 2,529 May-05-2020, 12:54 PM
Last Post: mart79
  [PySimpleGui] How to alter mouse click button of a standard submit button? skyerosebud 3 5,218 Jul-21-2019, 06:02 PM
Last Post: FullOfHelp
  [Tkinter] Radio button help Muzz 5 3,929 Apr-28-2019, 07:43 AM
Last Post: Muzz
  [Tkinter] Selected radio button in push button in Tkinter prashantfunde91 1 12,007 Jun-22-2017, 05:27 PM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020