Form submit callback not getting correct checkbox states

I’m trying to use st.checkboxes with forms. A user can select any number results from given choices.
When passing the states of the boxes in the form’s on_submit callbacks, the states are always false even though the user selects the boxes.
The snippet to repro:

def submit(boxes):
    print(boxes)

if __name__ == "__main__":
  with col1:
    st.header("Title")
    st.write("Text)
  
  with col2:
    st.title("Which of these are good recs:")
    with st.form("key"):
      b1 = st.checkbox("rec1", key="rec1")
      with st.expander("Exand Article"):
        st.write("details")

      b2 = st.checkbox("rec2", key="rec2")
      with st.expander("Exand Article"):
        st.caption("details")

      b3 = st.checkbox("rec3", key="rec4")
      with st.expander("Exand Article"):
        st.caption("details")
    
      b4 = st.checkbox("rec4", key="rec4")
      with st.expander("Exand Article"):
        st.caption("details")
    
      b5 = st.checkbox("rec5", key="rec5")
      with st.expander("Exand Article"):
        st.caption("details")
      
      submit_button = st.form_submit_button(label='Submit', on_click=submit, args=([b1, b2, b3, b4, b5],))

On submitting after selecting boxes, the callbacks always prints 5 false states. Can someone please point out what’s wrong here and how it can be fixed. thanks!

Hi @AyushExel :wave:

The value of each widget can be accessed as a session state variable following this syntax:

For a widget with a unique key ukey, you can get the value with st.session_state["ukey"].

In your example, the callback can be modified to print st.session_state['rec1'], st.session_state['rec2'], etc. And you can omit args in the form submit button.

Code

import streamlit as st

# to avoid typing st.session_state multiple times
state = st.session_state

def submit():
    st.write(
        state.rec1,
        state.rec2,
        state.rec3,
        state.rec4,
        state.rec5,
    )

col1, col2 = st.columns(2)

with col1:
    st.header("Title")
    st.write("Text")

with col2:
    st.title("Which of these are good recs:")
    with st.form("key"):
        b1 = st.checkbox("rec1", key="rec1")
        with st.expander("Exand Article"):
            st.write("details")

        b2 = st.checkbox("rec2", key="rec2")
        with st.expander("Exand Article"):
            st.caption("details")

        b3 = st.checkbox("rec3", key="rec3")
        with st.expander("Exand Article"):
            st.caption("details")

        b4 = st.checkbox("rec4", key="rec4")
        with st.expander("Exand Article"):
            st.caption("details")

        b5 = st.checkbox("rec5", key="rec5")
        with st.expander("Exand Article"):
            st.caption("details")

        submit_button = st.form_submit_button(label="Submit", on_click=submit)

Output

checkbox-callbacks

Happy Streamlit-ing! :balloon:
Snehan

Thanks… This worked