Updating Streamlit Button Widget Label Using Session State

63 Views Asked by At
# Initializing Session States
if 'counter' not in st.session_state:
    st.session_state.counter = 0
if 'start' not in st.session_state:
    st.session_state['start'] = False
if 'stop' not in st.session_state:
    st.session_state['stop'] = False
if 'refresh' not in st.session_state:
    st.session_state['refresh'] = False
if "button_label" not in st.session_state:
    st.session_state['button_label'] = "START"

#  Function to update current session
def update_session_state():
    if st.session_state.counter==1:    
        st.session_state['start'] = True
        st.session_state['button_label'] = "SUBMIT"

    elif st.session_state.counter == 2:
        # Set start to False
        st.session_state['start'] = False
        # Set stop to True
        st.session_state['stop'] = True
        # Rename button text
        st.session_state['button_label'] = "RELOAD"

    elif st.session_state.counter == 3:
        # Deactivate start & stop by setting them to False
        st.session_state['start'] = st.session_state['stop'] = False
        # Activate refresh to True
        st.session_state['refresh'] = True
        st.session_state.clear()

def update_label():
        if st.session_state.counter==0:
            st.session_state['button_label'] = "START"
        elif st.session_state.counter==1:
            st.session_state['button_label'] = "SUBMIT"
        elif st.session_state.counter==2:
            st.session_state['button_label'] = "RELOAD"

# Session States  @ the start
st.write("Before Button Press:", st.session_state)

# Initializing Button Text
button =  st.button(label=st.session_state['button_label'], 
                    key='button_press',
                    on_click=update_label)

if button:
    st.session_state.counter +=1
    update_session_state()
    # st.rerun()

    btn_text = st.session_state.button_label
    st.write("Current label should be ", btn_text)

    nl(3)
    st.write("current states on button press:", st.session_state)

I am having to click the button widget twice before it updates and the RELOAD returns a key error. I really need to figure out how to update that button accurately.

Anyone who can help please?

I created the button and initialized the label to START When the user clicks it the first time, the button label should change to STOP On another click, the button label should change to RELOAD On another click, the session should restart and the button label defaults back to START

I have combed the streamlit discussion community, documentation page, YouTube and of course AI tools but still doesn't behave as expected.

It is for a Quiz App I'm working on. Any help would be great, thanks!

0

There are 0 best solutions below