SingleChoice-type elements save data as integers - how can I access the corresponding text? #179
Answered
by
jobrachem
jobrachem
asked this question in
Alfred Q&A
-
Sometimes it would be much more convenient to work with the selected text of a |
Beta Was this translation helpful? Give feedback.
Answered by
jobrachem
Jan 20, 2022
Replies: 1 comment
-
Here's an example with extensive comments that walks you through the steps: import alfred3 as al
exp = al.Experiment()
@exp.member
class Demo(al.Page):
def on_exp_access(self):
self += al.SingleChoice("a", "b", name="my_single_choice_element")
@exp.member
class Show(al.Page):
def on_first_show(self):
# This is the SingleChoice element instance
# The pattern is: self.exp.PAGENAME.ELEMENTNAME
element = self.exp.Demo.my_single_choice_element
# This is the number of the selected choice, starting at 1
selected_choice_number = element.input
# This is a list of the available choices. These are instances of a
# private helper class _Choice
available_choices = element.choices
# We use the number of the selected choice to access the
# corresponding object. We have to subtract 1, because lists
# start indexing at 0, but our selected_choice_number
# starts at 1.
choice = available_choices[selected_choice_number - 1]
# Now we extract the "label" from the choice instance.
# The label is what is being displayed to participants, in this
# case the text.
selected_text = choice.label
self += al.Text(selected_text) # Displays the result
if __name__ == "__main__":
exp.run() To make the code a bit more organized, we can extract much of the functionality to its own function. In the following code example, I have put the relevant lines of code into the function import alfred3 as al
exp = al.Experiment()
def extract_input_label(element) -> str:
"""
Extracts the selected text from a SingleChoice element and
similar classes like SingleChoiceButtons.
"""
selected_choice_number = element.input
available_choices = element.choices
choice = available_choices[selected_choice_number - 1]
return choice.label
@exp.member
class Demo(al.Page):
def on_exp_access(self):
self += al.SingleChoice("a", "b", name="my_single_choice_element")
@exp.member
class Show(al.Page):
def on_first_show(self):
element = self.exp.Demo.my_single_choice_element
selected_text = extract_input_label(element) # Here we use the function defined above
self += al.Text(selected_text) # Displays the result
if __name__ == "__main__":
exp.run() |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
jobrachem
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's an example with extensive comments that walks you through the steps: