Function keeps resetting itself instead of moving forwards

Hi there,

I am building a widget that has this piece of code in a certain portion:

import streamlit as st

def choose_train_period():
    ticks = list(range(0, 100))
    max_tick = ticks[int(len(ticks)/2)]
    min_tick = min(ticks)
    start_tick, end_tick = st.select_slider(
        'Time interval to use for training',
        options=ticks,
        value=(min_tick, max_tick))
    submit = st.button('Submit', key='submit')

    if submit is True:
            st.markdown(f'The machine will be trained using data from tick {st.session_state["start_tick"]} '
                 f'to tick {st.session_state["test_tick"]} (included).')
            confirm = st.button('Confirm', key='confirm')
            if confirm is True:
                st.write('confirm')
            else:
                st.write('wait')

def init_world():
        form = st.empty()
        container = form.container()
        with container:
            train_period = choose_train_period()
            if train_period is True:
               st.markdown("Period selected")

init_world()

For some reason I really cannot understand, each time I click on “confirm” the whole function “choose_train_period” is reset. There are other aspects to this app that might interfere (it’s multistructured, I am also interacting with st.session_data, etc), but I’d really like to understand if anyone sees an issue here? I really out of my depth.

Hi @chiara, welcome to the community!! :wave: :partying_face:
The issue stems from your submit button. Clicking a button will set its value to True. When the app reruns on subsequent interactions (e.g. clicking the confirm button), the value of the initial submit button is reset to False, meaning the if block isn’t evaluated.

The solution is to replace submit = st.button('Submit', key='submit') with a checkbox which preserves its state:

submit = st.checkbox('Submit', key='submit')

Happy Streamlit-ing! :balloon:
Snehan

1 Like

Thanks Snehan! I decided to go for st.session_state (triggered by on_click) instead as I need it to stay memorised for further steps :slight_smile: