St.experimental_dialog and st.selectbox

I am curious about using a dialog to populate the options (and default) for a selectbox.

I created this dialog to add items to a list. The list is used as the options for a selectbox. I would like the first item in the list to be the “preselected item” if any.

import streamlit as st

# initialize session state
if 'items' not in st.session_state:
    st.session_state['items'] = []

@st.experimental_dialog("Add Item")
def add_item_dialog():
    st.text_input("Item", key="new_item")

    def add_item_submit():
        st.write("adding" + st.session_state['new_item'])
        st.session_state['items'] = st.session_state['items'] + [st.session_state['new_item']]
    
    if st.button("Submit", key="submit", on_click=add_item_submit):
        st.rerun()

if st.button("Add Item"):
    add_item_dialog()

def selectbox_onchange():
    st.info("selected " + st.session_state['selected_item'])

st.selectbox(label="Select Item", options=st.session_state['items'], index=0, key="selected_item", on_change=selectbox_onchange)

If I execute locally, I can add items using the dialog. However, even after adding several items (without selecting any), there is no preselected item. If I select an item, then add new items, the pre-selected item is set to the first one (expected value). Is there a way to to have the pre-selected item appropriately set immediately after the first addition without selecting an item?

(using streamlit 1.34.0; python 3.11.4)

I notice that if I remove the key and on_change arguments, that I get the behavior I expected. This seems to be about the behavior of the selectbox widget. My use case involves an on_change method, is there a way to achieve this?

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