randomal
randomal

Reputation: 6592

Web app in Streamlit with multiple questions per page

I'm working on a web app in Streamlit and I am looking for a way to have multiple questions per page (see below). At the moment if a user replies to the first question or to the second one, the app automatically loads the next set of questions. How can I change things so that the next set of questions is loaded only if the user replies to both the first question and to the second one?

The logic I am using at the moment is the following:

st.table(Text_lines)
col1, col2 = st.columns([1,1])
with col3:
    if st.button('Option 1'):
        st.session_state.option1 = 1
with col4:
    if st.button('Option 2'):
        pass

st.table(Other_text_lines)
col3, col4 = st.columns([1,1])
with col3:
    if st.button('Sensible (Q)'):
        st.session_state.sensibility = 1
with col4:
    if st.button('Not sensible (W)'):
        pass

enter image description here

Upvotes: 1

Views: 2298

Answers (1)

ferdy
ferdy

Reputation: 5024

One approach is to control the loading of questions by form. The user will press the submit button when done.

Example

import streamlit as st


if 'num' not in st.session_state:
    st.session_state.num = 0


choices1 = ['no answer', 'manila', 'tokyo', 'bangkok']
choices2 = ['no answer', 'thailand', 'japan', 'philippines']

qs1 = [('What is the capital of Japan', choices1),
    ('What is the capital of Philippines', choices1),
    ('What is the capital of Thailand', choices1)]
qs2 = [('What country has the highest life expectancy?', choices2),
    ('What country has the highest population?', choices2),
    ('What country has the highest oil deposits?', choices2)]


def main():
    for _, _ in zip(qs1, qs2): 
        placeholder = st.empty()
        num = st.session_state.num
        with placeholder.form(key=str(num)):
            st.radio(qs1[num][0], key=num+1, options=qs1[num][1])
            st.radio(qs2[num][0], key=num+1, options=qs2[num][1])          
                      
            if st.form_submit_button():
                st.session_state.num += 1
                if st.session_state.num >= 3:
                    st.session_state.num = 0 
                placeholder.empty()
            else:
                st.stop()


main()

Output enter image description here

Press submit and new set of questions will be loaded. enter image description here

Upvotes: 1

Related Questions