jeudi 29 juin 2023

Session state and button reloads in Streamlit not working as expected

I have a piece of code (written in python using streamlit) that creates a random number of clickable buttons (between 2 and 5) and the number of buttons are regenerated after the user clicks on one. I've tried having a textbox that always prints what buttons was clicked last but there's an issue when the current buttonLen is longer than the previous and the final button was clicked on, the textbox doesn't print the correct button (as it somehow loops over the shorter loop instead of the loop index being the max??), why is that?

# init click info as -1
if 'lastClick' not in st.session_state:
    st.session_state.lastClick = -1

if 'buttonLen' not in st.session_state:
    st.session_state.buttonLen = random.randint(2, 5)

fake = st.button("stupid", disabled=True)

if 'buttons' not in st.session_state:
    st.session_state.buttons = [fake] * 5

for i in range(st.session_state.buttonLen):
    st.session_state.buttons[i]= st.button(str(i))

for i in range(5):
    st.write(f"{st.session_state.buttons[i]} currentButton")
    if st.session_state.buttons[i]:
        # a button was clicked on! what do we do?
        # if the button is the same as before, keep that button info as true, if not: reset it.
        if i != st.session_state.lastClick:
            st.session_state.buttons[i] = False
        # update current click info
        st.session_state.lastClick = i
        # regen n
        st.session_state.buttonLen = random.randint(2, 5)
        break  

st.write(f"{st.session_state.lastClick} last clicked")

if prompt != "":
    prompt_container.empty()
    st.info(prompt)
    sub = sub_container.subheader("Continue your story by choosing from the options below")

i tried using the session state variables as seen in the code. i used a 'fake' button that is always disabled and so has value 'False' to populate the buttons list, and rewrite the buttons as fit when generating them, this didn't fix the bug.




Aucun commentaire:

Enregistrer un commentaire