Each widget’s value can be accessed by its key through st.session_state
. So ‘col1’ in the first row could be accessed from st.session_state['input_col10']
where the 0 on the end is the index of the first row.
If you look at the other two examples, you can see each row being added to a data source, rather than left on the screen as a widget. In general, I recommend the dataframe implementation, which is the first tab that loads when you go to that page. (I’m just in the middle of editing the example so col1, col2, col3, and col4 have become name, income, expense, and net, respectively.
import streamlit as st
import pandas as pd
st.write('# Solution using a dataframe')
# Create an empty dataframe on first page load, will skip on page reloads
if 'data' not in st.session_state:
data = pd.DataFrame({'name':[],'income':[],'expense':[],'net':[]})
st.session_state.data = data
# Show current data
st.dataframe(st.session_state.data)
st.write('#### Using form submission')
# Function to append inputs from form into dataframe
def add_dfForm():
row = pd.DataFrame({'name':[st.session_state.input_df_form_name],
'income':[st.session_state.input_df_form_income],
'expense':[st.session_state.input_df_form_expense],
'net':[st.session_state.input_df_form_income-st.session_state.input_df_form_expense]})
st.session_state.data = pd.concat([st.session_state.data, row])
# Inputs listed within a form
dfForm = st.form(key='dfForm', clear_on_submit=True)
with dfForm:
dfFormColumns = st.columns(4)
with dfFormColumns[0]:
st.text_input('name', key='input_df_form_name')
with dfFormColumns[1]:
st.number_input('income', step=1, key='input_df_form_income')
with dfFormColumns[2]:
st.number_input('expense', step=1, key='input_df_form_expense')
with dfFormColumns[3]:
pass
st.form_submit_button(on_click=add_dfForm)
st.write('#### Not using form submission')
# Function to append non-form inputs into dataframe
def add_df():
row = pd.DataFrame({'name':[st.session_state.input_df_name],
'income':[st.session_state.input_df_income],
'expense':[st.session_state.input_df_expense],
'net':[st.session_state.input_df_income-st.session_state.input_df_expense]})
st.session_state.data = pd.concat([st.session_state.data, row])
# Inputs created outside of a form (allows computing net for preview)
dfColumns = st.columns(4)
with dfColumns[0]:
st.text_input('name', key='input_df_name')
with dfColumns[1]:
st.number_input('income', step=1, key='input_df_income')
with dfColumns[2]:
st.number_input('expense', step=1, key='input_df_expense')
with dfColumns[3]:
st.number_input('net', step=1, key='input_df_net',
value = st.session_state.input_df_income-st.session_state.input_df_expense,
disabled=True)
st.button('Submit', on_click=add_df)