Streamlit Expander

The st.expander widget in Streamlit allows you to toggle visibility of a section of content. This is useful for organizing information and keeping the user interface clean by hiding less important details until the user chooses to view them.
Users can click on the expander header to expand or collapse the content inside it.
 
Need a Streamlit developer: Click here

Basic Syntax

				
					import streamlit as st

st.expander(label, expanded=False, *, icon=None, width="stretch")

				
			
ParameterTypeDefaultDescription
labelstrRequiredThe title shown on the expander bar
expandedboolFalseIf True, expander is open by default

Example usage of st.expander

Here, we demonstrate the basic usage of st.expander.
By clicking on the expander header, users can toggle the visibility of the content inside it.
				
					import streamlit as st

st.title("Streamlit Expander Example")

with st.expander("Click to expand"):
    st.write("This is the content inside the expander.")
    st.write("You can put any Streamlit elements here, such as text, charts, or images.")
    st.image("https://streamlit.io/images/brand/streamlit-logo-secondary-colormark-darktext.png", width=200)


				
			

Setting Default State

You can set the default state of the expander to be expanded or collapsed using the expanded parameter. In this example, the expander is set to be expanded by default.
				
					import streamlit as st

st.title("Expander with Default State")
with st.expander("This expander is expanded by default", expanded=True):
    st.write("The expander starts in the expanded state.")
    st.write("You can collapse it by clicking on the header.")


				
			

Multiple Expanders

You can have multiple expanders on the same page. Each expander operates independently, allowing users to expand or collapse them as needed.
				
					import streamlit as st

st.title("Multiple Expanders Example")

with st.expander("First Expander"):
    st.write("Content of the first expander.")

with st.expander("Second Expander"):
    st.write("Content of the second expander.")

with st.expander("Third Expander"):
    st.write("Content of the third expander.")


				
			

Nested Expanders

You can also nest expanders within each other. This allows for hierarchical organization of content.
				
					import streamlit as st


st.title("Nested Expanders Example")

with st.expander("Outer Expander"):
    st.write("This is the outer expander.")
    with st.expander("Inner Expander"):
        st.write("This is the inner expander.")
        st.write("You can nest expanders to create a hierarchy of content.")




				
			

Combining with Other Widgets

Expanders can be combined with other Streamlit widgets to create interactive sections. In this example, we include an input field and a button inside the expander.
				
					import streamlit as st

st.title("Expander with Other Widgets")

with st.expander("Interactive Section"):
    name = st.text_input("Enter your name:")
    if st.button("Submit"):
        st.write(f"Hello, {name}!")
    else:
        st.write("Please enter your name and click Submit.")


    

				
			

Expanders for Data visualization

Expanders are useful for organizing data visualizations. In this example, we include a chart inside an expander.
				
					import streamlit as st
import pandas as pd
import numpy as np


st.title("Expander with Data Visualization")

df = pd.DataFrame(np.random.randn(10, 3), columns=['A', 'B', 'C'])

with st.expander("Show Table"):
    st.dataframe(df)

with st.expander("Show Chart"):
    st.line_chart(df)


				
			

Dynamic Expanders with Loops

You can create dynamic expanders using loops. This is useful when you have a list of items and want to create an expander for each item.
				
					import streamlit as st

st.title("Dynamic Expanders Example")

students = {
    "Alice": [85, 90, 88],
    "Bob": [78, 82, 80],
    "Charlie": [92, 95, 94]
}


for student, scores in students.items():
    with st.expander(f"{student}'s Scores"):
        st.write(f"Scores: {scores}")
        st.write(f"Average Score: {sum(scores)/len(scores):.2f}")





				
			

Summary

The st.expander widget in Streamlit is a powerful tool for organizing content and improving the user interface. By using expanders, you can hide less important information until the user chooses to view it, keeping your app clean and user-friendly. You can customize the default state, nest expanders, combine them with other widgets, and create dynamic expanders using loops.
Expanders are particularly useful for sections of content that may not be immediately relevant to all users, such as detailed explanations, additional options, or supplementary data visualizations. By leveraging expanders effectively, you can enhance the overall user experience of your Streamlit applications.
 
 
 
Learn more about Streamlit: Click here
 
Watch Videos on Streamlit:
 

Leave a Reply

Your email address will not be published. Required fields are marked *