I have a form in Streamlit that looks something like this,
with st.form("my_form"):
text_input_1 = st.text_input("Input 1")
drop_down_1 = st.selectbox("Dropdown 1", ["Option 1", "Option 2"])
drop_down_2 = st.selectbox("Dropdown 2", ["Option 3", "Option 4"])
submitted = st.form_submit_button("Submit")
if submitted:
submission_state = st.text('Form Submitted!')
Now, I want my second dropdown field, i.e. drop_down_2 to appear only if a certain value in drop_down_1 is selected, say Option 1.
How can I achieve this?
I tried something like this, but it did not work.
with st.form("my_form"):
is_drop_down_2_disabled = True
text_input_1 = st.text_input("Input 1")
drop_down_1 = st.selectbox("Dropdown 1", ["Option 1", "Option 2"])
if drop_down_1 == 'Option 1':
is_drop_down_2_disabled = False
drop_down_2 = st.selectbox("Dropdown 2", ["Option 3", "Option 4"], disabled=is_drop_down_2_disabled)
submitted = st.form_submit_button("Submit")
if submitted:
submission_state = st.text('Form Submitted!')
I assume that this is because the variables within the form are not assigned any values until the Submit button is clicked.
The functionality of st.form is to not re-run the code until submitted. If you want that to happen, just don't put the button inside the form. You can split the form into two, it's not affecting the layout. However, if you want to store a value from the form and use it to change something, you need to use session state to save the button value:
import streamlit.session_state as ss
with st.form("my_form"):
ss.is_drop_down_2_disabled = True
text_input_1 = st.text_input("Input 1")
drop_down_1 = st.selectbox("Dropdown 1", ["Option 1", "Option 2"])
if drop_down_1 == 'Option 1':
ss.is_drop_down_2_disabled = False
drop_down_2 = st.selectbox("Dropdown 2", ["Option 3", "Option 4"], disabled=ss.is_drop_down_2_disabled)
ss.submitted = st.form_submit_button("Submit")
if ss.submitted:
submission_state = st.text('Form Submitted!')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With