Streamlit: Form Button has to be clicked twice

Summary

I have a Streamlit app with a form and a Submit button. However I have to press the Submit button twice always with the first texts.

Steps to reproduce

Code snippet:

import streamlit as st
import pandas as pd
import numpy as np

st.title('Text Annotation')

prolificid = st.text_input('Please Enter your Prolific ID')
st.write('Your Prolific ID: ', prolificid)

#df = pd.DataFrame(['Text 1', 'Text 2', 'Text 3', 'Text 4'], columns=['Text'])
df = pd.read_excel('../Annotation/Mini_Annotation/mini_annotation.xlsx')
df= df[:3] # can be imagined as a list of texts, e.g. df = ["text1..","text2"...]

result_df = pd.DataFrame(columns=["Column1", "Id","Text", "Label"])

if st.session_state.get('count') is None:
    st.session_state.count = 0
    st.session_state.label_list = []

with st.form("my_form"):
    st.write("Progress: ", st.session_state.count, "/", len(df))
    if st.session_state.count < len(df):
        text = df.iloc[st.session_state.count]['Text']
        st.write(text)
        label = st.selectbox("Classification:", ["HOF", "NOT","Not Sure"])
        submitted = st.form_submit_button("Submit & Next")
        if submitted:
            st.session_state.label_list.append(label)
            st.session_state.count += 1
    else:
        st.write("All done!")
        submitted = st.form_submit_button("Submit")
        result_df["Column1"] = df["Column1"]
        result_df["Id"] = df["Id"]
        result_df["Label"] = st.session_state.label_list
        result_df["Text"] = df["Text"]
        result_df.to_csv(f"annotated_file_{prolificid}.csv", sep=";")
        st.write("Here is the Completion Code: C1JP58BV")
        st.write("Here is Your Unique Completion Code: CQ85OH0C")
        if submitted:
            st.write(st.session_state.label_list)

If applicable, please provide the steps we should take to reproduce the error or specified behavior.

Expected behavior:

I expect so see the second text when I click the “Submit & Next”-Button. But always for the first text, I have to click it twice and I don’t know the reason for this.

Actual behavior:

For the start, the “Submit & Next”-button has to be clicked twice, otherwise it won’t switch to the second text. In the end it works, but it would be a better User Experience if it works from the first click on.

I recommend replacing this:

        if submitted:
            st.session_state.label_list.append(label)
            st.session_state.count += 1

with a callback function that does the same. As you have it now, when you click the button, the page reloads and it’s not until after the form that you change session state so you won’t utilize an updated count. If instead you update the count in a callback on the submit button, then the count will be updated before the page reloads and it will then load the form, seeing the incremented count.

Thanks!
I am new to programming, how does such a callback function look like?

def submit():
    st.session_state.label_list.append(st.session_state.label_input)
    st.session_state.count += 1


with st.form("my_form"):
    st.write("Progress: ", st.session_state.count, "/", len(df))
    if st.session_state.count < len(df):
        text = df.iloc[st.session_state.count]['Text']
        st.write(text)
        label = st.selectbox("Classification:", ["HOF", "NOT","Not Sure"], key='label_input')
        submitted = st.form_submit_button("Submit & Next", on_click=submit)

    else:
        # etc

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