Hi,
I am new to anvil and have created a set of 3 radio buttons using the designer and give them the same group_name (radioBar) with one of the buttons selected. I am trying to access the value selected using:
self.message_label.text = self.radioBar.get_group_value()
but get an error message:
AttributeError: ‘Form1’ object has no attribute 'radioBar’
Should I be doing something else?
The complete code is:
from ._anvil_designer import Form1Template
from anvil import *
class Form1(Form1Template):
def init(self, **properties):
# Set Form properties and Data Bindings.
self.init_components(**properties)
# Any code you write here will run when the form opens.
def BtnRun_click(self, **event_args):
self.message_label.text = self.radioBar.get_group_value()
Thanks in advance
Welcome to Anvil!
“radioBar” is a name the individual buttons use to stay in sync with each other. It’s not the name of an actual component on your form.
get_group_value
is a member of each radio button. So, use the name of any of the buttons, instead, e.g.,
self.message_label.text = self.radio_button_1.get_group_value()
See https://anvil.works/docs/client/components/basic#radiobutton
4 Likes
Thank you that is most helpful and I am now up and running.
However, is there a property of the group that holds the value of the radio button that has been selected without going through each one in turn?
Strictly speaking, the group is not an object, so it doesn’t have any properties. It’s just a string shared by all the buttons.
I think they did it this way so that the buttons could be distributed into other containing objects, and still remain connected to each other.
I have not seen a way to identify the selected RadioButton object, except by looking at each one in turn. This is simplest if you create a list
of the buttons, and loop over that list.
You could loop over every object on the form, but then you’d have to explicitly skip over the objects that were not of interest.
You can also use the radio buttons events to set one global variable when any of them changes.
1 Like
Yes! The event handler function receives the radio button itself as a parameter, so a single function could be used by all the buttons.