Skip to content

Instantly share code, notes, and snippets.

@sdhutchins
Last active July 18, 2023 20:38
Show Gist options
  • Save sdhutchins/fda9d1c0730839811abf618a190cf871 to your computer and use it in GitHub Desktop.
Save sdhutchins/fda9d1c0730839811abf618a190cf871 to your computer and use it in GitHub Desktop.
Create All option for multiselect
import streamlit as st
import pandas as pd
def select_options():
"""Select options based on the user's selection and update the session state.
This function is triggered when the selection of options changes. It checks if "All" is selected and updates
the session state accordingly. If "All" is selected, it sets the selected options to all options except "All",
and updates the maximum number of selections. If "All" is not selected, it updates the maximum number of selections
based on the available options.
Args:
None
Returns:
None
"""
if "selected_options" in st.session_state:
if "All" in st.session_state["selected_options"]:
st.session_state["selected_options"] = available_options[1:]
st.session_state["max_selections"] = len(available_options) - 1
else:
st.session_state["selected_options"] = []
st.session_state["max_selections"] = len(available_options) - 1
existing_genes = ["Gene1", "Gene2", "Gene3", "Gene4", "Gene5"]
clinvar_accession_ids = ["CLINVAR1", "CLINVAR2", "CLINVAR3", "CLINVAR4", "CLINVAR5"]
df = pd.DataFrame({"Gene": existing_genes, "Clinvar Accession ID": clinvar_accession_ids})
available_options = ["All"] + existing_genes
st.multiselect(
label="Select a Gene",
options=available_options,
key="selected_options",
max_selections=st.session_state["max_selections"],
on_change=select_options,
format_func=lambda x: "All" if x == "All" else x
)
if st.button("Clear Selection"):
st.session_state["selected_options"] = []
selected_genes = available_options[1:] if st.session_state["max_selections"] == 1 else st.session_state["selected_options"]
filtered_df = df[df["Gene"].isin(selected_genes)]
st.dataframe(filtered_df)
@sdhutchins
Copy link
Author

sdhutchins commented Jul 17, 2023

My gist is a modification of the example from Carlos D. Serrano at https://medium.com/streamlit/multi-select-all-option-in-streamlit-3c92a0f20526.

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment