Sidebar button doesn't work after first click

Hi, I have a problem when creating sidebar button. When I click analysis, it will show “Data loading” and “Visualizations” button. But when I click “Data loading” or"Visualizations" button, it will return to “Analysis” button. I have try to use session_state, but it doesn’t work. Could anyone help me solve this problem? Thank you in advance!

if st.button('Analysis'):
    if sidebar.button("Data loading"):
        show_basic_statistics()

    elif sidebar.button("Visualizations"):
        selected_subcontent = sidebar.radio("Select:", ["OptionA", "OptionB"])
        if selected_subcontent == "OptionA" :
            st.header('OptionA')
            opt = ["Option1", "Option2", "Option3"]
            option = st.selectbox("Select an option", opt)
            if option == Option1":

Using Session_state:

if "Data loading" not in st.session_state:
    st.session_state["Data loading"] = False
if "Visualizations" not in st.session_state:
    st.session_state["Visualizations"] = False
if st.button('Analysis'):
    if sidebar.button("Data loading"):
        st.session_state["Data loading"] = True
        show_basic_statistics()
        show_data_preview()
    if st.session_state["Visualizations"]:
    if sidebar.button(" Visualizations"):
        st.session_state["Visualizations"] = True
        selected_subcontent = sidebar.radio("Select:", ["OptionA", "OptionB"])

Hi @cjhkdxxn! :wave:

Would it be possible to send the full code so that we can better assess what may be going wrong here?

Thanks,
Charly

If I understand what you’re trying to accomplish properly, what you really want is a “stateful button”, so that when you press the button, it stays “pressed” until you press it again. While that is not the normal behavior of streamlit buttons (or most html buttons, actually), you might try the stateful_button module from streamlit_extras. Here’s an example:

import streamlit as st
from streamlit_extras.stateful_button import button


def show_basic_statistics():
    st.write("Basic statistics")


def show_data_preview():
    st.write("Data preview")


if button("Analysis", key="analysis"):
    with st.sidebar:
        if button("Data loading", key="loading"):
            show_basic_statistics()
            show_data_preview()

with st.sidebar:
    if button("Visualizations", key="visualizations"):
        selected_subcontent = st.radio("Select:", ["OptionA", "OptionB"])

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