How to have a button

Hi,
i have. a program that is doing something like that but after:

  • Clicking on update
  • When changing the period selectbox, I need to click on update again to print the code after the selectbox option.
    How should I do if I do not want that ie the Update data button update the data and while I do not click on this button, the calculation, will continue with the df dataframe that was loaded at the previous click ?
@st.cache_data
def load_data(google_data_load=True):
    # Calculation 
    return df

# Button to load data
if st.button("Update", type='primary'):
    df = load_data()
    st.dataframe(df)
    .... # Stuff are done here 

    periode = st.selectbox('Period', 
                               ['6 mois', '1 an', '3 ans'],
                               index= 1
                               )
    if periode=='6 mois':
        lag = 126
    elif periode=='1 an':
        lag = 252
    else:
        lag = 3*252

    st.dataframe(histo
                 .pct_change()
                 .rolling(lag)
                 .apply(lambda x: 100*cagr(x))
                 .dropna()
                 )

Hi @Jacques2101,

Ideally, I would have
a. loaded the df
b. asked the questions (selectbox)
c. and then had the button for the combined processing

However, as per your code, you would probably need to do it this way:

import pandas as pd

if "click_knt" not in st.session_state: st.session_state.click_knt = 0

if st.session_state.click_knt == 0: btntxt = "Update Period"
if st.session_state.click_knt == 2: btntxt = "Complete Processing"

dsbld = True if st.session_state.click_knt in (0,2) else False
if st.button(btntxt, type='primary'):
    if st.session_state.click_knt in (0,2): st.session_state.click_knt += 1 # click 1

    if st.session_state.click_knt in (0,1): 
        #load / create df here / do initial df processing if necessary...
        df = pd.DataFrame({"col1": [1, 2, 3], "col2": [4, 5, 6]})
        st.dataframe(df)

    if st.session_state.click_knt == 1:
        periode = st.selectbox('Period', ['6 mois', '1 an', '3 ans'], index= 1)
        if periode=='6 mois': lag = 126
        elif periode=='1 an': lag = 252
        else: lag = 3*252

        st.write("do other df processing here...")
        if st.session_state.click_knt == 1: st.session_state.click_knt += 1 # click 2

if st.session_state.click_knt > 2: st.write("all done...")

Cheers

Hi,

  • We import the Streamlit library as st.
  • Use st.button("Your Text")