How to reference widgets as objects on the page

When a widget is created on the page ie st.checkbox(“mycheckbox”) it’s very easy to base actions on the state of the object when it is clicked on etc. But if I have a loop that creates several checkboxes in a list, for example, that are just hanging out waiting to be clicked on, it’s not clear how the individual checkboxes are identified in functions. Example code:

//create the named checkboxes…
for name in namelist:

If there are 10 items in ‘namelist’ streamlit will present 10 checkboxes. If I also have a button on the screen that calls a function to return a list containing the names of the checkboxes that have been checked. I don’t see how I can check the value of each checkbox with out having a object reference for each one. I tried this:

def getCheckBoxValue(cbname)
return st.checkbox(cbname)

somehow this seems to recreate another checkbox when the function is called and then there is an error because the new checkbox will be a duplicate of the one previously made with that name.

The goal is to simply get a list of names cooresponding to the checkkboxes that are checked when a button is pressed.

I’m missing some very fundamental concept. Any help would be greatly appreciated.


Hi @TPMStreamer

Are you looking for something like this:

import streamlit as st

chkbxknt = st.number_input("No of Checkboxes to create", value=0, key="cbk")
if chkbxknt > 0:
    for i in range(chkbxknt):
        st.checkbox(f"Chkbox # {i}", key=f"cb{i}")

    if st.button("Find out my Ticked Checkboxes"):
        for i in range(chkbxknt):
            if st.session_state[f"cb{i}"] == True:
                st.caption(f"Checkbox {i} was pressed...")


1 Like

Oh man that’s exactly what I’m looking for. I guess I need to explore how the session_state mechanism works. It appears that it’s just happening behind the scenes - keeping up with all the widgets. Thanks for saving the day.

1 Like