Selectbox Reverts to Previous Value When Using the index Parameter

Example Code:
shapes = [“Circle”, “Square”, “Triangle”]

if “chosen_shape” not in st.session_state:
st.session_state[“chosen_shape”] = “Circle”

default_index = shapes.index(st.session_state[“chosen_shape”])

selected_shape = st.selectbox(“Select a shape:”, shapes, index=default_index)

st.write(“You selected:”, selected_shape)

st.session_state[“chosen_shape”] = selected_shape

I’m encountering an issue with a simple selectbox with index parameter. see the example code, , the selectbox resets its display back to the previous selection on every rerun. i understand when selectionbox is rerendered, the default index is still the previous values, so even when user select a new value, it immediately resets back to previous one because of index. so you have to eseentially select twice for a new item be selected. but Is this expected behavior when using the ‘index’ parameter? then how do we give a default value to selectbox when it’s rendered?

Hi,

try this: Using shapes.index(st.session_state[‘chosen_shape’]). This index is calculated each time the selection box is rendered, ensuring that the current value of chosen_shape is always displayed

import streamlit as st

shapes = ["Círculo", "Cuadrado", "Triángulo"]

# Inicializa la forma elegida en el estado de sesión si no existe

if "forma_elegida" not in st.session_state:

st.session_state["forma_elegida"] = "Círculo"

# Crea el cuadro de selección con el valor actual de forma_elegida

forma_seleccionada = st.selectbox("Seleccione una forma:", shapes, index=shapes.index(st.session_state["forma_elegida"]))

# Muestra la forma seleccionada

st.write("Ha seleccionado:", forma_seleccionada)

# Actualiza el estado de sesión con la nueva forma seleccionada

st.session_state["forma_elegida"] = forma_seleccionada

This is a major problem in streamlit… Streamlit confuses itself with the index it is called with and the index of the new option that was selected just now…

Replace the call to st.selectbox() in your code with the following gist (be careful with the argument order, they are not the same)

thanks, this is helpful

1 Like

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