“Hello everyone! I’m new to Streamlit and I need some help! In the code below, how can I ensure that the widget variables remain saved, even when navigating through different pages of the app? When I return to the page with the code, the values reset to zero! Can you help me?”
def process_form():
# Inicializa os valores no st.session_state se eles ainda não existirem
if 'n_ha' not in st.session_state:
st.session_state['n_ha'] = 0
if 'p_ha' not in st.session_state:
st.session_state['p_ha'] = 0
if 'k_ha' not in st.session_state:
st.session_state['k_ha'] = 0
if 's_ha' not in st.session_state:
st.session_state['s_ha'] = 0
# Define o formulário
with st.form(key='my_form'):
# Define os widgets dentro do formulário
n_ha = st.number_input('Digite a quantidade de Nitrogênio (N) por ha:', min_value=0, format='%d', key='n_ha_input', value=st.session_state['n_ha'])
p_ha = st.number_input('Digite a quantidade de Fósforo (P) por ha:', min_value=0, format='%d', key='p_ha_input', value=st.session_state['p_ha'])
k_ha = st.number_input('Digite a quantidade de Potássio (K) por ha:', min_value=0, format='%d', key='k_ha_input', value=st.session_state['k_ha'])
s_ha = st.number_input('Digite a quantidade de Enxofre (S) por ha:', min_value=0, format='%d', key='s_ha_input', value=st.session_state['s_ha'])
# Adiciona um botão submit ao formulário
submit_button = st.form_submit_button(label='Simular menores custos')
# Se o botão submit for pressionado e o formulário for submetido
if submit_button:
# Armazena os valores dos widgets no st.session_state
st.session_state['n_ha'] = n_ha
st.session_state['p_ha'] = p_ha
st.session_state['k_ha'] = k_ha
st.session_state['s_ha'] = s_ha
process_form()
# Defina as variáveis globalmente para uso posterior
n_ha = st.session_state['n_ha']
p_ha = st.session_state['p_ha']
k_ha = st.session_state['k_ha']
s_ha = st.session_state['s_ha']