Search code examples
pythonwidgetstreamlit

How to create a button that adds a new widget every time I click it with streamlit?


I have a button called "Add", I would like to let the user create a new selectbox widget every time he clicks it so that if the user decides to press the "Add" button 10 times, 10 selectboxes will be created. this is the button:

        engine.add_clicked  = st.button("Add",on_click = add_callback,help="Add a new test", key="Add", args=(engine, tests_body_container,))

this is the on_click function:

def add_callback(engine, container):
      with container:
            st.selectbox("options?", ("a", "b", "c"))

The problem is that it only works once, it adds one selectbox and then nothing else happens. image of the streamlit page

I found a solution that uses session states but I haven't managed to make it work. The solution I found: https://discuss.streamlit.io/t/adding-widgets-with-button/39953/2


Solution

  • I hope this piece of code can help.

    Basically you need to add the key you want to the session before using them. Secondly update the session number in the callback.

    import streamlit as st
    
    
    if 'selectbox_count' not in st.session_state:
        st.session_state.selectbox_count = 0
    
    def add_callback():
        st.session_state.selectbox_count += 1
    
        
    engine = st.empty()  # Assuming engine is a Streamlit container
    add_clicked = engine.button("Add", on_click=add_callback, help="Add a new test", key="Add")
    
    for i in range(st.session_state.selectbox_count):
        st.selectbox(f"Options {i + 1}:", ("a", "b", "c"))