- Spec files
pypi-streamlit
Describes: pkg:pypi/streamlit@1.49.x
- Description
- A faster way to build and share data apps
- Author
- tessl
- Last updated
layout-containers.md docs/
1# Layout and Containers23Layout management and container elements for organizing app structure and controlling element positioning. These components provide the foundation for creating well-structured, responsive Streamlit applications.45## Capabilities67### Column Layouts89Create multi-column layouts for side-by-side element placement.1011```python { .api }12def columns(spec, gap="small"):13"""14Insert containers laid out as side-by-side columns.1516Parameters:17- spec (int or sequence): Number of columns or sequence of column widths18- gap (str): Gap size between columns ('small', 'medium', 'large')1920Returns:21list: List of column containers22"""23```2425### Tab Layouts2627Organize content into selectable tabs.2829```python { .api }30def tabs(tab_labels):31"""32Insert containers separated into tabs.3334Parameters:35- tab_labels (list): List of tab labels3637Returns:38list: List of tab containers39"""40```4142### Generic Containers4344Multi-element containers for grouping related content.4546```python { .api }47def container(height=None, border=False):48"""49Insert a multi-element container.5051Parameters:52- height (int): Container height in pixels53- border (bool): Show container border5455Returns:56DeltaGenerator: Container object57"""5859def expander(label, expanded=False):60"""61Insert a multi-element container that can be expanded/collapsed.6263Parameters:64- label (str): Expander label65- expanded (bool): Initial expanded state6667Returns:68DeltaGenerator: Expander container object69"""7071def popover(label, help=None, disabled=False, use_container_width=False, icon=None):72"""73Insert a popover container that appears on click.7475Parameters:76- label (str): Popover trigger button label77- help (str): Optional tooltip text78- disabled (bool): Disable the popover trigger79- use_container_width (bool): Use full container width for trigger80- icon (str): Optional icon for trigger button8182Returns:83DeltaGenerator: Popover container object84"""85```8687### Sidebar8889Dedicated sidebar area for navigation and controls.9091```python { .api }92# Sidebar container object with all main interface methods93sidebar: DeltaGenerator94```9596### Forms9798Container for batching widget interactions and submissions.99100```python { .api }101def form(key, clear_on_submit=False, border=True):102"""103Create a form that batches elements together with a submit button.104105Parameters:106- key (str): Unique form identifier107- clear_on_submit (bool): Clear form values after submission108- border (bool): Show form border109110Returns:111DeltaGenerator: Form container object112"""113114def form_submit_button(label="Submit", help=None, on_click=None, args=None, kwargs=None, type="secondary", disabled=False, use_container_width=False, icon=None):115"""116Display a form submit button (only works inside st.form).117118Parameters:119- label (str): Button label120- help (str): Optional tooltip text121- on_click (callable): Function to call when submitted122- args (tuple): Arguments to pass to on_click function123- kwargs (dict): Keyword arguments to pass to on_click function124- type (str): Button type ('primary' or 'secondary')125- disabled (bool): Disable the button126- use_container_width (bool): Use full container width127- icon (str): Optional icon name128129Returns:130bool: True if form was submitted, False otherwise131"""132```133134### Utility Containers135136Special-purpose containers for specific layout needs.137138```python { .api }139def empty():140"""141Insert a single-element container for placeholder content.142143Returns:144DeltaGenerator: Empty container object145"""146147def divider():148"""149Display a horizontal rule divider.150151Returns:152None153"""154```155156### Progress and Status Containers157158Containers for displaying progress and status information.159160```python { .api }161def progress(value, text=None):162"""163Display a progress bar.164165Parameters:166- value (float): Progress value between 0.0 and 1.0167- text (str): Optional progress text168169Returns:170DeltaGenerator: Progress bar object171"""172173def status(label, expanded=False, state="running"):174"""175Display a status container to show progress of long-running tasks.176177Parameters:178- label (str): Status label179- expanded (bool): Show contents by default180- state (str): Status state ('running', 'complete', 'error')181182Returns:183DeltaGenerator: Status container object184"""185186def spinner(text="In progress..."):187"""188Temporarily display a message with spinner while executing a block of code.189190Parameters:191- text (str): Message to display192193Returns:194ContextManager: Spinner context manager195"""196```197198## Usage Examples199200### Multi-Column Layouts201202```python203import streamlit as st204205# Equal-width columns206col1, col2, col3 = st.columns(3)207208with col1:209st.header("Column 1")210st.write("Content for column 1")211st.button("Button 1")212213with col2:214st.header("Column 2")215st.write("Content for column 2")216st.selectbox("Options", ["A", "B", "C"])217218with col3:219st.header("Column 3")220st.write("Content for column 3")221st.slider("Value", 0, 100, 50)222223# Custom column widths224col1, col2 = st.columns([2, 1]) # 2:1 ratio225226with col1:227st.write("This column is twice as wide")228229with col2:230st.write("Narrow column")231232# Columns with different gaps233st.subheader("Large Gap Between Columns")234col1, col2 = st.columns(2, gap="large")235236with col1:237st.info("Column with large gap")238239with col2:240st.info("Another column")241```242243### Tab Organization244245```python246# Create tabs247tab1, tab2, tab3 = st.tabs(["π Charts", "π Data", "βοΈ Settings"])248249with tab1:250st.header("Charts Tab")251252# Sample chart253import pandas as pd254import numpy as np255256chart_data = pd.DataFrame(257np.random.randn(20, 3),258columns=['a', 'b', 'c']259)260st.line_chart(chart_data)261262with tab2:263st.header("Data Tab")264st.dataframe(chart_data)265266with tab3:267st.header("Settings Tab")268st.checkbox("Enable notifications")269st.selectbox("Theme", ["Light", "Dark", "Auto"])270```271272### Expandable Content273274```python275# Basic expander276with st.expander("See explanation"):277st.write("""278This is additional content that can be hidden or shown.279Perfect for detailed explanations, advanced options, or FAQ sections.280""")281st.code('''282def hello():283print("Hello, World!")284''')285286# Expander with initial expanded state287with st.expander("Advanced Configuration", expanded=True):288st.slider("Advanced parameter 1", 0, 100, 50)289st.checkbox("Enable advanced feature")290st.text_input("Custom setting")291```292293### Sidebar Usage294295```python296# Add content to sidebar297st.sidebar.title("Navigation")298st.sidebar.markdown("Use the controls below:")299300# Sidebar inputs301page = st.sidebar.selectbox(302"Choose a page:",303["Home", "Data Analysis", "Visualization", "Settings"]304)305306if page == "Data Analysis":307# Sidebar filters for data analysis308st.sidebar.header("Filters")309310date_range = st.sidebar.date_input(311"Select date range:",312value=[pd.Timestamp('2023-01-01'), pd.Timestamp('2023-12-31')]313)314315categories = st.sidebar.multiselect(316"Select categories:",317["Category A", "Category B", "Category C"],318default=["Category A"]319)320321# Main content based on sidebar selection322st.title(f"{page} Page")323st.write(f"Content for {page}")324```325326### Form Containers327328```python329# Contact form example330with st.form("contact_form"):331st.write("Contact Us")332333name = st.text_input("Name *", placeholder="Enter your full name")334email = st.text_input("Email *", placeholder="your@email.com")335subject = st.selectbox("Subject", [336"General Inquiry",337"Technical Support",338"Bug Report",339"Feature Request"340])341message = st.text_area("Message *", placeholder="Enter your message here...")342343# Form will only submit when this button is clicked344submitted = st.form_submit_button("Send Message", type="primary")345346if submitted:347if name and email and message:348st.success("Message sent successfully!")349st.balloons()350else:351st.error("Please fill in all required fields (*)")352353# Form with clear on submit354with st.form("survey_form", clear_on_submit=True):355st.write("Quick Survey")356357rating = st.slider("How would you rate our service?", 1, 5, 3)358feedback = st.text_area("Additional feedback:")359recommend = st.checkbox("Would you recommend us to others?")360361if st.form_submit_button("Submit Survey"):362st.success("Thank you for your feedback!")363st.write(f"Rating: {rating}/5")364st.write(f"Would recommend: {'Yes' if recommend else 'No'}")365```366367### Containers and Placeholders368369```python370# Generic container371with st.container():372st.write("This content is in a container")373st.info("Containers help organize related content")374375# Container with border376with st.container(border=True):377st.write("This container has a visible border")378col1, col2 = st.columns(2)379with col1:380st.metric("Metric 1", "1,234", "12")381with col2:382st.metric("Metric 2", "5,678", "-5")383384# Empty placeholder for dynamic content385placeholder = st.empty()386387# Later, replace the placeholder content388import time389for i in range(5):390placeholder.text(f"Loading... {i+1}/5")391time.sleep(1)392393placeholder.success("Loading complete!")394```395396### Progress and Status397398```python399# Progress bar400progress_bar = st.progress(0)401status_text = st.empty()402403for i in range(100):404# Update progress405progress_bar.progress(i + 1)406status_text.text(f'Progress: {i+1}%')407time.sleep(0.01)408409status_text.text('Processing complete!')410411# Status container412with st.status("Processing data...", expanded=True) as status:413st.write("Loading dataset...")414time.sleep(1)415st.write("Cleaning data...")416time.sleep(1)417st.write("Running analysis...")418time.sleep(1)419status.update(label="Analysis complete!", state="complete", expanded=False)420421# Spinner context manager422with st.spinner('Computing complex calculation...'):423time.sleep(2) # Simulate long computation424st.success('Calculation finished!')425```426427### Popover Usage428429```python430# Simple popover431with st.popover("Open popover"):432st.markdown("Hello World π")433name = st.text_input("What's your name?")434if name:435st.write(f"Nice to meet you, {name}!")436437# Popover with custom button438with st.popover("βοΈ Settings", help="Click to configure settings"):439st.checkbox("Enable notifications")440st.selectbox("Language", ["English", "Spanish", "French"])441theme = st.radio("Theme", ["Light", "Dark", "Auto"])442443if st.button("Apply Settings"):444st.success("Settings applied!")445```446447### Responsive Layout Patterns448449```python450# Responsive metric dashboard451col1, col2, col3, col4 = st.columns(4)452453metrics = [454("Revenue", "$125K", "12%"),455("Users", "2.8K", "-5%"),456("Conversion", "3.2%", "0.8%"),457("Retention", "87%", "2%")458]459460for col, (label, value, delta) in zip([col1, col2, col3, col4], metrics):461with col:462st.metric(label, value, delta)463464# Two-column layout with different content465left_col, right_col = st.columns([2, 1])466467with left_col:468st.subheader("Main Content")469st.write("This is the main content area with more space.")470471# Chart or main visualization472chart_data = pd.DataFrame(473np.random.randn(50, 3),474columns=['A', 'B', 'C']475)476st.line_chart(chart_data)477478with right_col:479st.subheader("Sidebar Content")480st.write("Controls and filters go here.")481482# Controls483show_data = st.checkbox("Show raw data")484chart_type = st.selectbox("Chart type", ["Line", "Area", "Bar"])485486if show_data:487st.dataframe(chart_data.tail())488```