Panel not clearing on form submit

Hi All,

Newbie to ST and first post. Trying to build a Q&A form in ST.

  • Used option_menu (sidebar)
  • on click of Section 1, I get what I need on display panel. (Section 1, Domain selection…)
  • on form submit (click of Start button), I get the display question BUT I also get ‘Section 1, domain selection’ at the bottom.
  • This should be another form and on selection of checkbox, The value is always None (As shown in print statement).

Could you please let me know what am I doing incorrect here. Possibly some rookie mistake.

import streamlit as st
from streamlit_option_menu import option_menu
from typing import Dict, List
import random
import time
import json
from pathlib import Path
import uuid


def left_sidebar(user):
    with st.sidebar:
        st.sidebar.title(f"Welcome, {user}")
        selected_option = option_menu(
            menu_title="Home",
            options=[
                "Home",
                "Section 1",
                "Settings",
            ],
            icons=["house", "book", "gear"],
            menu_icon="cast",
            default_index=0,
        )
    return selected_option


def main():
    page = left_sidebar("John Doe")
    if page == "Home":
        introduction = "Introduction Text"
        st.markdown(introduction)
    elif page == "Section 1":
        st.header("Section 1")
        section_1()
    elif page == "Settings":
        st.header("Working on it")
        st.markdown("<p>Work In Progress....</p>", unsafe_allow_html=True)


def section_1():
    with st.form("my_form"):
        domain = st.selectbox(
            "Select Domain",
            [
                "Domain 1",
                "Domain 2",
            ],
        )

        st.form_submit_button("Start", type="primary", on_click=display_question)


def get_question() -> Dict:
    uniq = str(uuid.uuid4())[:20]
    return {
        "summary": "Please answer the question - " + uniq,
        "question": "What is the capital of France? - "  + uniq,
        "options": {"A": "Paris", "B": "London", "C": "Berlin", "D": "Madrid"},
        "answer": "A",
        "explanation": "Google it!",
        "categories": ["Cat 1", "Cat 2"],
    }


def display_question():
    question: Dict = get_question()

    with st.form("q_form"):
    # with st.container():
        start_time = time.time()
        passage = question["summary"]
        st.markdown(
            f"""
            <div style="border: 2px solid white; padding: 10px; border-radius: 5px; font-size: 30px; word-wrap: break-word;">
                <b>Passage:</b> <br>
                <p>{passage}.</p>
            </div>
            """,
            unsafe_allow_html=True,
        )

        categories = question["categories"]
        columns = st.columns(len(categories))
        for col, category in zip(columns, categories):
            col.checkbox(label=category, value=True, disabled=True)

        st.divider()

        ques = question["question"]
        options = question["options"]
        ops = [f"{k} : {v}" for k, v in options.items()]

        st.markdown(
            f"""
            <div style="border: 2px solid white; padding: 10px; font-size: 30px; border-radius: 5px;">
                <b>Question:</b> <br>
                <p>{ques}.</p>
            </div>
            """,
            unsafe_allow_html=True,
        )

        st.markdown(
            """
            <style>
            .stRadio > label {
                font-size: 40px !important;
            }
            </style>
            """,
            unsafe_allow_html=True,
        )

        student_answer = st.radio(
            label="NOT IMPORTANT",
            options=ops,
            index=None,
            horizontal=False,
            label_visibility="hidden",
        )

        col1, col2 = st.columns(2)

        with col1:
            difficulty = st.slider("Difficulty level?", 0, 10, 5)

        with col2:
            genuine = st.slider(
                "How Genuine was the passage and question/options?", 0, 10, 5
            )

        st.form_submit_button(
            "Submit",
            type="primary",
            on_click=submit_answer,
            args=[question, start_time, student_answer, difficulty, genuine],
            kwargs={},
        )


def submit_answer(question: Dict, start_time, student_answer, difficulty, genuine):
    print(f"Student Answer: [{student_answer}]. Difficulty: [{difficulty}], Genuine [{genuine}]")

    end_time = time.time()
    time_taken_in_sec = end_time - start_time

    answer = question["answer"]
    if answer == student_answer:
        st.success("Correct Answer!")
    else:
        st.error("Incorrect Answer!")

    st.write(f"Time taken: {time_taken_in_sec:.2f} seconds")

    explanation = question["explanation"]
    st.caption(
        f"""
        _Answer_:
            <bi>{answer}</bi>
        """,
        unsafe_allow_html=True,
    )
    st.caption(
        f"""
        _Explanation_:
            <p>{explanation}</p>
        """,
        unsafe_allow_html=True,
    )

    question["attempted"] = True
    question["solved_correct"] = student_answer == question["answer"]
    question["time_taken_in_sec"] = time_taken_in_sec

    st.session_state["last_question"] = question

    if question["solved_correct"]:
        st.success("Correct Answer!")
    else:
        st.error("Incorrect Answer!")

    st.write(f"Time taken: {time_taken_in_sec:.2f} seconds")


if __name__ == "__main__":
    main()

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