Keeping session state with buttons from a loop

Hi all,

I’m not sure what I’m missing - just can’t see it. Maybe it’s something obvious, but I would be grateful for your help.

I’m having a number of buttons, which I call through a for loop and then those buttons show plot, write stuff etc. I also have a slider and an input value - which when edited, they change plots. However, in that case I am loosing those details that were shown on a button click - as I do not preserve session state.

I want to preserve session state of a button click, so that when I update slider value the writing that cam out of a button is preserved. Here is simplified version which I can not make to work.

Can you help out please?

import streamlit as st

buttons = [ st.button("A", key="A"), st.button("B", key="B"), 
           st.button("C", key="C"), st.button("D", key="D")]


for i, b in enumerate(buttons): 
    if buttons[i]:
        st.session_state['button'] = buttons[i]
        
for i, b in enumerate(buttons): 
    if buttons[i]:
        if st.session_state['button'] == True:
            st.write(f"{[i]} was clicked.")        

st.slider('Test', value = [0.0,1.0], step = 0.1, key = 'T')

Like this maybe?

import streamlit as st

if 'button' not in st.session_state:
    st.session_state['button'] = 0
    
buttons = [ st.button("A"), st.button("B"), 
           st.button("C"), st.button("D")]


for i, b in enumerate(buttons): 
    if buttons[i]:
        st.session_state['button'] = i+1
             
st.slider('Test', value = [0.0,1.0], step = 0.1, key = 'T')

st.write(f"Button {st.session_state['button']} was clicked.")
2 Likes

Thank you for the quick reply!

This looks very promising, and it this example does what I imagined.
Of course, I will have to place it to the main/real code and see the final outcome, and let you know :slight_smile:

1 Like

Finally!

At first, couldn’t make it to work as I had another issue, but now it seems to work just fine!
Thank you heaps!

This will make user experience much better :slight_smile:

1 Like

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.