Hello, I’ve tried to develop interactive quiz based on Streamlit.
I have list of prepared questions and answers.
My code is:
data is DataFrame as like:
Question Answer type_of_button add_other_option
What is your favourite country? ['USA','Canada'] checkbox Yes
Do you have pets? ['Yes', 'No'] radiobutton No
Do you like travelling? ['Yes', 'No'] radiobutton No
What is your favourite meal? ['Meat', 'Salad'] checkbox Yes
and the function to show Q&A on the form is:
import streamlit as st
def display_question(index):
question = data.loc[index, 'Question']
provided_answers = eval(data.loc[index, 'Answer'])
button_type = data.loc[index, 'type_of_button']
add_other_option = data.loc[index, 'add_other_option']
st.write(question)
user_answer_lst = []
if button_type == 'radiobutton':
current_answer = st.radio("", options=provided_answers, key=f"radio_{index}")
user_answer_lst.append(current_answer)
else:
if add_other_option == 'Yes':
provided_answers.append('Other')
user_answer_lst = []
for opt in provided_answers:
answer_check_box = st.checkbox(opt, key=f"{index}_{opt}")
if answer_check_box:
if opt == 'Other':
additional_option = st.text_input("Please specify:", key=f"{opt}_{index}")
if additional_option:
user_answer_lst.append(additional_option)
else:
user_answer_lst.append(opt)
# Update the session state with the collected answers
if len(st.session_state['answers']) <= index:
st.session_state['answers'].append(user_answer_lst)
else:
st.session_state['answers'][index] = user_answer_lst
to call this function I use streamlit.form:
with st.form(key='my_form'):
if st.session_state['current_question'] < len(data) - 1:
display_question(st.session_state['current_question'])
if st.form_submit_button('Next'):
st.session_state['current_question'] += 1
else:
display_question(st.session_state['current_question']) # Display the last question again
if st.form_submit_button("Generate Output"):
questions = data['Question'].tolist()
answers = st.session_state['answers']
qa_pairs = {q: a for q, a in zip(questions, answers)}
st.write(qa_pairs)
Problem is:
if user selects Other than form doesn’t show additional st.text_input where is possible to print answer manually.
How is it possible to fix this issue? Thanks