Hello:
I have a code like this:
selected_option = st.selectbox(“Select an option”, options, key=“search_option”,index=None,)
How can I make a contitional sentence that is only execute when a selection is made, and don’t do nothing when no selection is made?
I’ve tred something like:
if selected_option!=“None”:
#dosometing
But it doesn’t work…
Depending on what kind of thing you’re trying to do, you can check for None
or use a callback.
Check for None
instead of "None"
.
import streamlit as st
selected_option = st.selectbox("Select an option", ["A","B","C"], key="search_option", index=None,)
if selected_option is not None:
st.write(f"You selected {selected_option}.")
st.button("Rerun")
Use a callback:
import streamlit as st
def notification():
st.toast(f"You selected {st.session_state.search_option}.")
selected_option = st.selectbox("Select an option", ["A","B","C"], key="search_option", index=None, on_change=notification)
st.button("Rerun")
I’ve include another button in both examples to highlight the difference: when you use the conditional to check for None
, the code in the if block will execute on every rerun. (The message persists.) If you use a callback, the callback code will only execute in reaction to the changed selection, but not again if the user clicks elsewhere in the app. (The message is only one-time, in reaction to a change.)