About st.radio and st.button in my app

Summary

When I click the “next” button, it append automatically the first choice(st.radio) in the wrong_answer_list although I haven’t chosen an answer. Also, I had to click twice the button on the first question before it would go to the next question(this only applies on the first question).

Steps to reproduce

with st.form(key='quiz_form'):
    if st.session_state["current_quiz_index"] < len(selected_questions):
        current_question = selected_questions[st.session_state["current_quiz_index"]]
        st.write(current_question["question"])
        user_choice = st.radio("", current_question["options"])

        if st.form_submit_button('Next'):
            if user_choice == current_question["answer"]:
                st.session_state["correct_answer"] += 1
                st.session_state.correct_answer_list.append(user_choice)
            else:
                st.session_state.wrong_answer += 1
                wrong_answer_data = {
                    'question': current_question["question"],
                    'user_ans': user_choice,
                    'correct_ans': current_question["answer"]
                }
                st.session_state.wrong_answer_list.append(wrong_answer_data)

Expected behavior:

I expected the user to choose their answer before it appends to wrong_answer_list or correct_answer_list. Also, only click the next button once when the first question appears.

Actual behavior:

After the user click the next button, the user couldn’t chose the answer because it automatically append the answer that was chosen when the next page loads. Also, in the first page or question, I have to click the next button twice.

Debug info

  • Streamlit version: (get it with $ streamlit version)
  • Python version: (get it with $ python --version)
  • Using Conda? PipEnv? PyEnv? Pex?
  • OS version:
  • Browser version:

Requirements file

Using Conda? PipEnv? PyEnv? Pex? Share the contents of your requirements file here.
Not sure what a requirements file is? Check out this doc and add a requirements file to your app.

Links

  • Link to your GitHub repo:
  • Link to your deployed app:

Additional information

If needed, add any other context about the problem here.

Hi @Jun

Often times, when the button needs to be clicked twice in order to see the desired effect, this is typically resolved by defining a callback function and then using the callback function from st.button such that when the button is clicked the desired effect is achieved with 1 click.

Hope this helps!

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.