Change choice in st.selectbox by clicking on a button in a side bar

Hi,
I am quite new to streamlit. I am seaching for a wayto change the existing choice / pick of a st.selectbox element by clicking on a button in the sidebar.

Example: st.selectbox has selected “A” and a chart “A” is rendered. I want to click on a button “B” in the side bar which changes the selection to “B” in the main window and st.selectbox, so that chart “B” is displayed in the main window.

Is there an easy way to realize this?

Thank you very much for your help

import pandas as pd
import streamlit as st

default_value = "A"

if st.sidebar.button("A"):
    default_value = "A"

if st.sidebar.button("B"):
    default_value = "B"

if st.sidebar.button("C"):
    default_value = "C"


df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6], "C": [7, 8, 9], "D": [10, 11, 12]})


choices = ["A", "B", "C"]
selected = st.selectbox("Select an object", choices, index=choices.index(default_value))

st.write(f"You selected {selected}")

st.line_chart(df, x="D", y=selected, use_container_width=True)

Setting the default_value in the sidebar seems to work well.

2 Likes

Thank you very much, I will give it a try.

Hi @Mareus

I just realized that @blackary already had a great example code in the comments while I was creating one.

Here’s the one that I came up with:

Code

import streamlit as st
import pandas as pd

# Callback function for A and B
def onClick(selection_input):
    if selection_input == 'A':
        st.session_state['selection'] = 0
    if selection_input == 'B':
        st.session_state['selection'] = 1

# Initialize the session state
if 'selection' not in st.session_state:
    st.session_state['selection'] = 0

# Select box
selected = st.selectbox('Make a selection:', ('A', 'B'), index=st.session_state['selection'])

# Buttons
st.button('A', on_click=onClick, args='A')
st.button('B', on_click=onClick, args='B')

# Conditional display of data visualization
if selected == 'A':
    st.subheader('Data visualization for A')
    chart_data = pd.DataFrame(
        [0.31, 0.46, 0.86, 0.91, 0.96],
        columns=['A'])
    st.line_chart(chart_data)

if selected == 'B':
    st.subheader('Data visualization for B')
    chart_data = pd.DataFrame(
        [10, 26, 37, 56, 85],
        columns=['B'])
    st.line_chart(chart_data)

Screencast

Screen Recording 2566-04-18 at 00_scaling-0.6_fps-20_speed-10.0_duration-0-12

2 Likes

Thank you very much. Both versions are exactly what I needed. Thank you so much to you two.

1 Like

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