I am locally running streamlit: Streamlit version 1.34.0 and Python version 3.9
The relevant code is the following:
import streamlit as st
import pandas as pd
# Initialize session state variables
def initialize_ss_variables():
# Ensure 'data' is initialized in session state
if 'data' not in st.session_state:
# Initialize with a DataFrame with default empty rows
st.session_state['data'] = pd.DataFrame({
"column1": ["", "", "", "", ""],
"column2": ["", "", "", "", ""],
"column3": [False, False, False, False, False],
"column4": ["first", "first", "first", "first", "first"]
})
def main():
initialize_ss_variables()
with st.form(key='data_editor_form', border=False):
edited_df = st.data_editor(
st.session_state['data'],
column_order=["column1", "column2", "column3", "column4"],
use_container_width=True,
hide_index=True,
column_config={
"column4": st.column_config.SelectboxColumn(
label="Column 4",
options=["first", "second", "third"],
default="first",
required=True,
),
"column3": st.column_config.CheckboxColumn(
label="Column 3",
),
"column1": st.column_config.Column(
label="Column 1",
),
"column2": st.column_config.Column(
label="Column 2",
)
},
key="data_editor_key"
)
submit_button = st.form_submit_button(
label='Save Changes',
type='primary',
use_container_width=True
)
if submit_button:
st.write(edited_df)
if __name__ == "__main__":
main()
The problem:
When you click on the submit button just after editing (lets say you just wrote something in the first column, or even wrote two or three things, and the last thing you wrote is still open while you press the submit button) then any of these three things can happen, apparently very randomly:
- The last thing does not get saved in the dataframe and is not displayed when st.write(edited_df), but it does appear in the st.form, so if you click the submit button again, then it saves it.
- The last thing you wrote does not get saved, and it disappears from st.form, so you lose it forever.
- The last thing you wrote gets saved along with the rest of the things you wrote, and lets say everything works as expected.
I have tried different things but I cannot figure out, first how to fix this annoying behaviour, and second how is it possible that the behaviour is so random?
Usually if after writing a few words in different rows of the first column for example, you click outisde the dataframe, and then click on the submit button, it saves all correctly. not always though, but seems to be related to the fact that you click submit button while still editing the field [Update: actually it seems to happen the same, I was trying to make a connection but I dont think now that it is much connected]. Also probably is related to the speed with which you write and go press the submit button [or maybe not…]. The issue is that, user-experience wise, everybody would click directly the submit button after just writing the word, so it is a big issue that the submit button says “save changes” but it does not save them.