Skip to content

🗳️  No-Default Selectbox

Submitted by Zachary Blackwood

Summary

Just like st.selectbox, but with no default value -- returns None if nothing is selected.

Meant to be a solution to https://github.com/streamlit/streamlit/issues/949

Functions

selectbox

A selectbox that returns None unless the user has explicitly selected one of the options. All arguments are passed to st.selectbox except for no_selection_label, which is used to specify the label of the option that represents no selection.

Parameters:

Name Type Description Default
no_selection_label str

The label to use for the no-selection option. Defaults to "---".

required
Source code in src/streamlit_extras/no_default_selectbox/__init__.py
@extra
def selectbox(*args, **kwargs):
    """
    A selectbox that returns None unless the user has explicitly selected one of the
    options. All arguments are passed to st.selectbox except for `no_selection_label`, which is
    used to specify the label of the option that represents no selection.

    Args:
        no_selection_label (str): The label to use for the no-selection option. Defaults to "---".
    """
    no_selection_label, _args, _kwargs = _transform_arguments(*args, **kwargs)

    result = st.selectbox(*_args, **_kwargs)
    if result == no_selection_label:
        return None
    return result

Import:

from streamlit_extras.no_default_selectbox import selectbox # (1)!
  1. You should add this to the top of your .py file 🛠

Examples

example

def example():
    st.write(
        """
        This is an example of a selectbox that returns None unless the user has
        explicitly selected one of the options.

        The selectbox below has no default value, so it will return None until the
        user selects an option.
        """
    )
    result = selectbox("Select an option", ["A", "B", "C"])
    st.write("Result:", result)

    result = selectbox(
        "Select an option with different label",
        ["A", "B", "C"],
        no_selection_label="<None>",
    )
    st.write("Result:", result)
Output (beta)