Checkbox dynamic true and false like toggle on / off

Hi.
I am quite new to streamlit. I’m looking such a feature that work like this:

st.checkbox("dummy_name",key='dummy_key')

When dummy_name checked, then st.session_state[‘dummy_key’] = TRUE
When dummy_name unchecked, then st.session_state[‘dummy_key’] = FALSE

how do i resolve this?
Or is there any feature that suitable to my needs?

Thanks

Hi @Cignitor

Here’s a code snippet that you can use to achieve what you’re looking for:

import streamlit as st

# callback to update 'test' based on 'check'
def flip():
    if st.session_state["check"]:
        st.session_state["test"] = True
    else:
        st.session_state["test"] = False

if "test" not in st.session_state:
    st.session_state["test"] = True

st.checkbox(
    "Flip the switch", value=st.session_state["test"], key="check", on_change=flip
)

st.write(st.session_state["test"])

checkbox-state

This is from a previous post with a solution by @snehankekre: Session state issue with st.checkbox - #2 by snehankekre

Hope this helps!

Thanks!

Currently i have 9 checkboxes. Do i have to create 9 flip() according to each key?

Hi,

You could achieve this by using a for loop to iterate through a list of 9 values/elements and use f-strings to generate unique keys and session state variable names f’check_{element}’ and f’test_{element}’, respectively.

This would give the same effect of manually creating 9 separate callback functions in less lines of code.

Hope this helps!

This is how i create st.checkbox

kelengkapan_klaim = {
    'suket_dokter':{
        'name':'Surat Keterangan Dokter',
        'key':'kelengkapan_klaim_suket_dokter'
    },
    'invoice':{
        'name':'Invoice',
        'key':'kelengkapan_klaim_invoice'
    },
    'kwitansi':{
        'name':'Kwitansi / Official Receipt / Bukti Bayar',
        'key':'kelengkapan_klaim_kwitansi'
    },
    'tax_invoice':{
        'name':'Tax Invoice (bila ada. Bila tidak ada maka tetap diceklis)',
        'key':'kelengkapan_klaim_tax_invoice'
    },
    'resume_medis':{
        'name':'Resume Medis / Discharge Summary',
        'key':'kelengkapan_klaim_resume_medis'
    },
    'billing_details':{
        'name':'Rincian biaya, perawatan, dan obat-obatan selama Rawat Inap',
        'key':'kelengkapan_klaim_billing_details'
    },
    'hasil_lab':{
        'name':'Hasil Laboratorium dan analisa dokter (baca rontgen, MRI,CT Scan, dll)',
        'key':'kelengkapan_klaim_hasil_lab'
    }
    ,'ktp':{
        'name':'Copy KTP Tertanggung',
        'key':'kelengkapan_klaim_ktp_tertanggung'
    },
    'rekening':{
        'name':'Copy Buku Rekening Tabungan untuk pembayaran klaim',
        'key':'kelengkapan_klaim_buku_rekening'
    }

}
        for item in kelengkapan_klaim:
            st.checkbox(kelengkapan_klaim[item]['name'],key=kelengkapan_klaim[item]['key'],on_change=calc_kelengkapan_klaim)

Then, here’s the function:

def calc_kelengkapan_klaim():
    count_true = 0 #to have it presented in st.progress
    count_checkbox=0 # count_true / count_checkbox
    for item in st.session_state:        
        if 'kelengkapan_klaim' in item: #this is where st.checkbox is
            print("Item is {}".format(item))
            if st.session_state[item]:
                st.session_state[item]=False
            else:
                st.session_state[item]=True
            # count_checkbox+=1
            # print("Checking session state {} its value is {}".format(item,st.session_state[item]))
            # count_true+=1 if st.session_state[item] else count_true + 0
    
    print("count_true is {}. count_checkbox is {}".format(count_true,count_checkbox))

When i click one of the checkboxes, the function altered the rest checkboxes and vice versa.

The key in:

st.checkbox("dummy_name", key='dummy_key')

is already the session_state key of that checkbox.

  • Install the latest streamlit
  • Do not use on_change in the checkbox.

Try the following code.

code

# Build checkbox.
for item in kelengkapan_klaim:
    st.checkbox(kelengkapan_klaim[item]['name'], value=False, key=kelengkapan_klaim[item]['key'])

st.markdown('---')

# Get status.
for item in kelengkapan_klaim:
    st.write(f'{kelengkapan_klaim[item]["name"]} state value is {st.session_state[kelengkapan_klaim[item]["key"]]}.')

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