- Spec files
pypi-streamlit
Describes: pkg:pypi/streamlit@1.16.x
- Description
- The fastest way to build and share data apps
- Author
- tessl
- Last updated
layout-containers.md docs/
1# Layout and Containers23Functions for organizing content and creating sophisticated multi-panel layouts. These containers help structure your Streamlit application by grouping related content, creating responsive layouts, and managing form submissions.45## Capabilities67### Basic Containers89Fundamental container types for organizing and grouping content.1011```python { .api }12def container() -> DeltaGenerator:13"""14Create an invisible container for grouping elements.1516Returns:17DeltaGenerator: Container object for adding elements18"""1920def empty() -> DeltaGenerator:21"""22Create a placeholder container that can be filled later.2324Returns:25DeltaGenerator: Empty container that can be populated programmatically26"""27```2829#### Usage Example3031```python32import streamlit as st3334# Container for grouping related content35with st.container():36st.write("This content is in a container")37st.button("Container button")3839# Empty placeholder that can be filled later40placeholder = st.empty()4142# Later in the code, fill the placeholder43placeholder.text("This text was added to the placeholder!")44```4546### Column Layouts4748Create responsive multi-column layouts for side-by-side content arrangement.4950```python { .api }51def columns(spec, gap: str = "small") -> List[DeltaGenerator]:52"""53Create a set of columns for side-by-side layout.5455Parameters:56- spec: Number of columns (int) or list of column widths57- gap: Gap size between columns ("small", "medium", "large")5859Returns:60List[DeltaGenerator]: List of column containers61"""62```6364#### Usage Example6566```python67import streamlit as st6869# Equal width columns70col1, col2, col3 = st.columns(3)7172with col1:73st.header("Column 1")74st.write("Content for first column")7576with col2:77st.header("Column 2")78st.write("Content for second column")7980with col3:81st.header("Column 3")82st.write("Content for third column")8384# Custom width columns (ratios)85left_col, middle_col, right_col = st.columns([1, 2, 1])8687with left_col:88st.write("Narrow left")8990with middle_col:91st.write("Wide middle column")9293with right_col:94st.write("Narrow right")9596# Large gap between columns97col_a, col_b = st.columns(2, gap="large")9899with col_a:100st.metric("Revenue", "$1.2M")101102with col_b:103st.metric("Users", "1,234")104```105106### Tabbed Interface107108Create tabbed interfaces for organizing content into separate views.109110```python { .api }111def tabs(tab_labels: List[str]) -> List[DeltaGenerator]:112"""113Create a tabbed interface.114115Parameters:116- tab_labels: List of tab names/labels117118Returns:119List[DeltaGenerator]: List of tab containers120"""121```122123#### Usage Example124125```python126import streamlit as st127import pandas as pd128import numpy as np129130# Create tabs131tab1, tab2, tab3 = st.tabs(["Data", "Charts", "Settings"])132133with tab1:134st.header("Data View")135data = pd.DataFrame(np.random.randn(10, 3), columns=["A", "B", "C"])136st.dataframe(data)137138with tab2:139st.header("Charts View")140st.line_chart(data)141st.bar_chart(data)142143with tab3:144st.header("Settings")145st.selectbox("Theme", ["Light", "Dark"])146st.checkbox("Enable notifications")147```148149### Expandable Sections150151Create collapsible sections to organize content hierarchically.152153```python { .api }154def expander(label: str, expanded: bool = False) -> DeltaGenerator:155"""156Create an expandable/collapsible container.157158Parameters:159- label: Text displayed on the expander header160- expanded: Whether the expander is initially expanded161162Returns:163DeltaGenerator: Expandable container164"""165```166167#### Usage Example168169```python170import streamlit as st171172# Basic expander173with st.expander("See explanation"):174st.write("""175This is a detailed explanation that is hidden by default.176Users can click to expand and see this content.177""")178179# Initially expanded expander180with st.expander("Configuration Options", expanded=True):181st.slider("Temperature", 0, 100, 50)182st.selectbox("Model", ["GPT-3", "GPT-4"])183184# Multiple expanders for organized content185with st.expander("📊 Data Analysis"):186st.write("Data analysis content here")187st.line_chart([1, 2, 3, 4, 5])188189with st.expander("🔧 Settings"):190st.checkbox("Debug mode")191st.number_input("Batch size", value=32)192193with st.expander("ℹ️ Help & Documentation"):194st.markdown("""195## Getting Started1961. Upload your data1972. Configure parameters1983. Run analysis199""")200```201202### Sidebar203204Special container for sidebar content (accessed via `st.sidebar`).205206```python { .api }207sidebar: DeltaGenerator208# Access sidebar through st.sidebar209# All regular widgets and containers work in sidebar context210```211212#### Usage Example213214```python215import streamlit as st216217# Sidebar content218st.sidebar.title("Navigation")219page = st.sidebar.selectbox("Choose page:", ["Home", "Data", "Results"])220221st.sidebar.markdown("---")222st.sidebar.write("Settings")223debug_mode = st.sidebar.checkbox("Debug mode")224batch_size = st.sidebar.slider("Batch size", 1, 100, 32)225226# Sidebar with sections227with st.sidebar:228st.markdown("### Filters")229230category = st.selectbox("Category:", ["All", "A", "B", "C"])231date_range = st.date_input("Date range:")232233st.markdown("### Options")234show_raw_data = st.checkbox("Show raw data")235export_format = st.radio("Export format:", ["CSV", "JSON"])236237# Main content area238st.title(f"Current page: {page}")239if debug_mode:240st.write(f"Debug: Batch size is {batch_size}")241```242243### Forms244245Group related inputs and control when they trigger app reruns.246247```python { .api }248def form(key: str, clear_on_submit: bool = False) -> DeltaGenerator:249"""250Create a form container to batch widget interactions.251252Parameters:253- key: Unique key for the form254- clear_on_submit: Whether to clear form inputs after submission255256Returns:257DeltaGenerator: Form container258"""259260def form_submit_button(label: str = "Submit", help: str = None, on_click=None, args=None, kwargs=None, type: str = "primary", disabled: bool = False, use_container_width: bool = False) -> bool:261"""262Display a form submit button (must be used inside a form).263264Parameters:265- label: Text displayed on the submit button266- help: Tooltip text shown on hover267- on_click: Callback function executed on submit268- args: Arguments passed to callback function269- kwargs: Keyword arguments passed to callback function270- type: Button type ("primary" or "secondary")271- disabled: Whether the button is disabled272- use_container_width: Whether to use full container width273274Returns:275bool: True if submit button was clicked, False otherwise276"""277```278279#### Usage Example280281```python282import streamlit as st283284# Simple form285with st.form("my_form"):286st.write("User Information")287name = st.text_input("Name")288age = st.number_input("Age", min_value=0, max_value=120)289email = st.text_input("Email")290291# Form submission292submitted = st.form_submit_button("Submit")293294if submitted:295st.success(f"Form submitted for {name}, age {age}, email {email}")296297# Form with sections and validation298with st.form("contact_form", clear_on_submit=True):299st.markdown("### Contact Information")300301col1, col2 = st.columns(2)302with col1:303first_name = st.text_input("First Name")304phone = st.text_input("Phone")305with col2:306last_name = st.text_input("Last Name")307email = st.text_input("Email")308309st.markdown("### Message")310subject = st.selectbox("Subject", ["General Inquiry", "Support", "Feedback"])311message = st.text_area("Message", height=100)312313# Submit with validation314if st.form_submit_button("Send Message"):315if first_name and last_name and email and message:316st.success("Message sent successfully!")317st.balloons()318else:319st.error("Please fill in all required fields")320321# Form with custom submit handling322def handle_submission():323st.session_state.form_submitted = True324325with st.form("custom_form"):326data = st.text_input("Enter data:")327328submitted = st.form_submit_button(329"Process Data",330on_click=handle_submission331)332333if submitted and st.session_state.get("form_submitted", False):334st.write(f"Processing: {data}")335st.session_state.form_submitted = False336```337338### Advanced Layout Patterns339340Combine containers for sophisticated layouts.341342#### Usage Example343344```python345import streamlit as st346347# Header section348header_container = st.container()349with header_container:350st.title("Dashboard")351col1, col2, col3 = st.columns(3)352with col1:353st.metric("Total Users", "1,234", "+5%")354with col2:355st.metric("Revenue", "$12.3K", "+12%")356with col3:357st.metric("Growth", "8.2%", "+1.2%")358359# Main content with sidebar navigation360with st.sidebar:361st.selectbox("Time Period", ["Last 7 days", "Last 30 days", "Last 90 days"])362st.multiselect("Filters", ["Region A", "Region B", "Region C"])363364# Tabbed main content365tab1, tab2 = st.tabs(["Overview", "Details"])366367with tab1:368# Overview content with expandable sections369with st.expander("Charts", expanded=True):370col1, col2 = st.columns(2)371with col1:372st.line_chart([1, 3, 2, 4, 5])373with col2:374st.bar_chart([2, 1, 3, 4, 2])375376with st.expander("Data Table"):377st.dataframe({"A": [1, 2, 3], "B": [4, 5, 6]})378379with tab2:380# Details content381st.write("Detailed view content here")382383# Footer placeholder384footer = st.empty()385footer.markdown("---")386footer.caption("Last updated: 2024-01-01")387```388389## Layout Best Practices390391- Use **columns** for side-by-side content392- Use **tabs** for different views of the same data393- Use **expanders** for optional/detailed information394- Use **forms** to batch related inputs and reduce reruns395- Use **sidebar** for navigation and persistent controls396- Use **containers** to group related elements logically