Reset input parameters back to default

I was trying to take some number input from the user but Iโ€™m trying to add a reset values button which resets the input back to its original state

Code snippet:

        with col1:
            # values after the user changes parameters
            inp1 = 0.5
            inp2 = 10.28
            inp3 = 0.5
            inp4 = 1.0

            min_vug_area = st.number_input("Min Vug Area", value=inp1)
            max_vug_area = st.number_input("Max Vug Area", value=inp2)
            min_circ_ratio = st.number_input("Min Circ Ratio", value=inp3)
            max_circ_ratio = st.number_input("Max Circ Ratio", value=inp4)

Expected behavior:
There should be a reset button in the same column which resets the value back to default i.e. 0.5,10.28,0.5,1.0

Thank you in advanceโ€‹:two_hearts::two_hearts:

Hey @Abhishek_Mallick :wave:

Iโ€™ve added session_state() elements where needed for this to work:

import streamlit as st

if "reset" not in st.session_state:
    st.session_state.reset = False

with st.container():
    default_values = {"inp1": 0.5, "inp2": 10.28, "inp3": 0.5, "inp4": 1.0}

    inp1 = default_values["inp1"] if st.session_state.reset else st.session_state.get("inp1", default_values["inp1"])
    inp2 = default_values["inp2"] if st.session_state.reset else st.session_state.get("inp2", default_values["inp2"])
    inp3 = default_values["inp3"] if st.session_state.reset else st.session_state.get("inp3", default_values["inp3"])
    inp4 = default_values["inp4"] if st.session_state.reset else st.session_state.get("inp4", default_values["inp4"])

    st.session_state.inp1 = st.number_input("Min Vug Area", value=inp1)
    st.session_state.inp2 = st.number_input("Max Vug Area", value=inp2)
    st.session_state.inp3 = st.number_input("Min Circ Ratio", value=inp3)
    st.session_state.inp4 = st.number_input("Max Circ Ratio", value=inp4)

    # Reset button
    if st.button("Reset values"):
        st.session_state.reset = True  # Mark reset as True if button is pressed
        st.experimental_rerun()  # Rerun the script
        st.session_state.reset = False  # Reset the reset flag

Have a look at this quick gif :slight_smile:

Recording 2023-09-03 at 13.07.53

Let me know if youโ€™d need anything else.


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