Session-state issue

“Hello everyone, I’m getting started with Streamlit and I’m facing a difficulty. In my form, I have a field labeled ‘ID’ that will receive the code I want to query, and a query button. Upon clicking this button, it will return some information about this ID.
There’s another ‘Value’ field that will receive the value to be altered. However, when I enter the ID and click on ‘Query’, it returns the desired values, but when I input a value in the ‘Value’ field, the previously returned information gets cleared.
How can I solve this issue?”


import mysql.connector
import json
import streamlit as st
import pandas as pd
import numpy as np
import time
import locale
import datetime
from decimal import Decimal
from streamlit_folium import st_folium
from databasecm2 import DatabaseHandler


def version_data():
    config = db_handler.load_config()
    
    version=config['version']
    date_version=config['date_v']

    return version, date_version


def show_negotiation():
    #st.write(negotiation_result)
    with st.container():
        col1, col2, col3 = st.columns(3)
        with col1:
            if negotiation_result[0][1] is not None:
                st.text(f'Data criação: {negotiation_result[0][1].strftime("%d/%m/%Y %H:%M")}')
            else:
                st.text(f'Data criação: Nulo')
        with col2:
            if negotiation_result[0][2] is not None: 
                st.text(f'Data atualização: {negotiation_result[0][2].strftime("%d/%m/%Y %H:%M")}')
            else:
                st.text(f'Data atualização: Nulo')
        with col3:
            if negotiation_result[0][3] is not None:
                st.text(f'Data exclusão: {negotiation_result[0][3].strftime("%d/%m/%Y %H:%M")}')
            else:
                st.text(f'Data exclusão: Nulo')

    with st.container():
        col1, col2, col3 = st.columns(3)
        with col1:
            if negotiation_result[0][13] is not None:
                valor_decimal = Decimal(negotiation_result[0][13])
                valor_formatado = format(valor_decimal, '.2f')
                valor_formatado = valor_formatado.replace('.', '@').replace(',', '.').replace('@', ',')

                st.text(f'Aluguel: {valor_formatado}')
            else:
                st.text(f'Aluguel: Nulo')

if __name__ == "__main__":
    st.set_page_config(
        page_title="Data Correction db LocK",
        page_icon="🎲",
        layout="wide",
        initial_sidebar_state="expanded",
        menu_items={
            'Get Help': 'https://www.lock-datacorrection.com/help',
            'Report a bug': "https://www.lock-datacorrection.com/bug",
            'About': "# Data Correction db LocK"
        }
    )
    
    with open('style.css') as f:
        st.markdown(f'<style>{f.read()}</style>', unsafe_allow_html=True)

    # Instância da classe DatabaseHandler
    db_handler = DatabaseHandler()
    
    # Declara variaveis
    global id_neg
    
    btn_callnegotiation_press = True
    btn_run_press = True
    fvalue_to_be_changed = 0
        
    locale.setlocale(locale.LC_ALL, 'pt_BR.UTF-8')

    data_version_app = version_data()
   
    st.title('Loc:orange[K] _Data_ _Correction_ ')
    st.subheader(':white[Correção nos valores de aluguel dos imóveis]')
    st.text(f'Versão {data_version_app[0]} {data_version_app[1]}')
    
    with st.container():
        col1, col2, col3 = st.columns([3, 1, 1])
        with col1:
            id_neg = st.text_input('ID',
                                   placeholder='Digite o ID da negociação'
                                   )
        with col2:
            value_to_be_changed = st.text_input('Valor',
                                                placeholder='Novo valor do aluguel',
                                                value='0'
                                                )

        btn_callnegotiation = st.button('Consulta')

        # Mostra dados da negociação
        if btn_callnegotiation:
            # Inicialize a variável `id_neg` no estado da sessão.
            id_neg = st.session_state.get('id_neg', None)
            negotiation_result = db_handler.load_negotiation(id_neg)   
            show_negotiation()
            btn_callnegotiation_press = False
            # Atualiza a variável de estado de sessão `id_neg` com o novo valor.
            st.session_state['id_neg'] = id_neg
        
        if value_to_be_changed != '':
            value_to_be_changed = value_to_be_changed.replace(',', '.')
            fvalue_to_be_changed = float(value_to_be_changed)        

        if fvalue_to_be_changed != 0:
            btn_run_press = False
                 
        btn_run = st.button('Executar',
                               disabled=btn_run_press)

        if btn_run:
            with st.spinner(text='Aguarde...'):
                time.sleep(2)
            #codigo a ser implementado

This is due to the normal behavior of streamlit buttons Button behavior and examples - Streamlit Docs

If you want a button that acts like a checkbox (i.e. stays “pressed” until you click it again), you might consider using https://extras.streamlit.app/Stateful%20Button

1 Like