How to Use Streamlit: A Comprehensive Guide to All Commands

Introduction: The Streamlit Ecosystem

The world of data applications has been transformed by tools that simplify the creation of interactive web interfaces. Among these, Streamlit has emerged as a revolutionary framework for Python developers, offering an incredibly streamlined path from data to interactive web application. With its intuitive API and focus on developer experience, Streamlit has become the tool of choice for data scientists, machine learning engineers, and analysts who want to quickly transform their Python scripts into shareable web applications without the complexity of traditional web development frameworks.

"What drew me to Streamlit wasn't just its simplicity, but how it retained the Python-first workflow I was accustomed to. I found myself deploying interactive dashboards in hours that would have taken weeks with traditional frameworksβ€”all without having to learn HTML, CSS, or JavaScript."

The Core Differences: Architecture and Philosophy

Before diving into specific commands, it's essential to understand what makes Streamlit unique. Unlike traditional web frameworks that separate frontend and backend development, Streamlit introduces a radically simplified approach where Python code executes from top to bottom, reactively re-running when inputs change. This dataflow model eliminates the need for callbacks, request handling, or state management code. Every Streamlit application is essentially a Python script that runs from start to finish, with special commands that render UI elements and handle interactivity through a reactive execution model.

Evolution and Maturity

  • First released in October 2019
  • Rapidly gained popularity in the data science community
  • Acquired by Snowflake in March 2022
  • Now a mature framework with extensive component ecosystem

Streamlit: Core Display Elements

Streamlit's display commands are the foundation of any application, allowing you to present text, data, and visual elements with minimal code. These functions are designed to work with common Python data types and objects, enabling seamless integration with your existing data workflows.


# Streamlit Core Display Elements Example
import streamlit as st
import pandas as pd
import numpy as np

# Title and text elements
st.title("Streamlit Application Demo")
st.header("Display Elements Overview")
st.subheader("Text and Markdown")

# Regular text and markdown
st.text("This is regular text - plain and simple.")
st.markdown("**Markdown** is _supported_ with `formatting`.")

# Information hierarchy
st.caption("This is a small caption text.")
st.write("st.write() is the Swiss Army knife for displaying content.")

# Code display
st.code("def hello_world():\n    print('Hello, Streamlit!')", language="python")

# Data display
st.subheader("Data Elements")
df = pd.DataFrame({
    'Column 1': np.random.randn(5),
    'Column 2': np.random.randn(5),
    'Column 3': np.random.choice(['A', 'B', 'C'], 5)
})

# Various ways to display data
st.dataframe(df)  # Interactive dataframe
st.table(df)  # Static table
st.json({"name": "Streamlit", "status": "Awesome"})
st.metric(label="Temperature", value="70 Β°F", delta="1.2 Β°F")
    

Streamlit: Media and Visualization Commands

Streamlit excels in presenting visualizations and media, offering native support for popular Python visualization libraries like Matplotlib, Plotly, and Altair. These commands make it effortless to incorporate charts, images, videos, and audio into your applications, creating rich, interactive experiences that bring data to life.


# Streamlit Media and Visualization Example
import streamlit as st
import matplotlib.pyplot as plt
import plotly.express as px
import altair as alt
import numpy as np
import pandas as pd

# Example data
data = pd.DataFrame({
    'x': np.arange(100),
    'y': np.random.normal(0, 15, 100),
    'category': np.random.choice(['A', 'B', 'C'], 100)
})

# Matplotlib chart
st.subheader("Matplotlib Integration")
fig, ax = plt.subplots()
ax.scatter(data['x'], data['y'], c=data['y'], cmap='viridis')
ax.set_title("Matplotlib Scatter Plot")
st.pyplot(fig)

# Plotly chart
st.subheader("Plotly Integration")
fig_plotly = px.scatter(data, x='x', y='y', color='category', 
                       title="Plotly Scatter Plot")
st.plotly_chart(fig_plotly)

# Altair chart
st.subheader("Altair Integration")
chart = alt.Chart(data).mark_circle().encode(
    x='x',
    y='y',
    color='category',
    tooltip=['x', 'y', 'category']
).interactive()
st.altair_chart(chart, use_container_width=True)

# Media elements
st.subheader("Media Elements")
st.image("https://www.example.com/sample_image.jpg", 
         caption="Sample Image", use_column_width=True)
st.audio("https://www.example.com/sample_audio.mp3")
st.video("https://www.example.com/sample_video.mp4")

# Map visualization
st.subheader("Geographic Data")
map_data = pd.DataFrame({
    'lat': [37.76, 37.77, 37.78],
    'lon': [-122.4, -122.5, -122.6]
})
st.map(map_data)
    

Streamlit: Interactive Widgets

What truly sets Streamlit apart is its intuitive system for creating interactive elements. With simple function calls, you can add various input widgets that automatically trigger re-execution of your script when their values change. This reactive programming model eliminates the need for explicit event handling, making it remarkably straightforward to create dynamic, responsive applications that adapt to user input in real-time.


# Streamlit Interactive Widgets Example
import streamlit as st
import pandas as pd
import numpy as np

st.title("Interactive Widgets Demo")

# Basic input widgets
name = st.text_input("Enter your name", "Streamlit User")
st.write(f"Hello, {name}!")

# Numeric inputs
age = st.number_input("Age", min_value=0, max_value=120, value=30)
height = st.slider("Height (cm)", 100.0, 220.0, 170.0)
st.write(f"You are {age} years old and {height} cm tall.")

# Selection widgets
st.subheader("Selection Widgets")

# Select box
option = st.selectbox(
    "Choose a programming language",
    ["Python", "R", "Julia", "JavaScript"]
)

# Multiselect
options = st.multiselect(
    "What frameworks do you know?",
    ["Streamlit", "Flask", "Django", "FastAPI", "React"],
    ["Streamlit"]
)

# Radio buttons
level = st.radio(
    "Experience level",
    ["Beginner", "Intermediate", "Advanced"]
)

# Checkbox
agree = st.checkbox("I agree to the terms and conditions")
if agree:
    st.write("Thank you for agreeing!")

# Expander
with st.expander("Click to see more information"):
    st.write("This text is hidden by default and appears when expanded.")
    st.image("https://www.example.com/detailed_info.jpg")

# Date and time inputs
st.subheader("Date and Time Inputs")
d = st.date_input("When is your birthday?")
t = st.time_input("Meeting time")

# Color picker
color = st.color_picker("Choose a color", "#00f900")
st.write(f"You selected color: {color}")

# File uploader
st.subheader("File Upload")
uploaded_file = st.file_uploader("Choose a CSV file", type="csv")
if uploaded_file is not None:
    data = pd.read_csv(uploaded_file)
    st.write("Data Preview:")
    st.dataframe(data.head())
    
# Camera input
camera_photo = st.camera_input("Take a photo")
if camera_photo:
    st.image(camera_photo, caption="Your photo")
    

Streamlit: Layout and Containers

Controlling the visual organization of your application is essential for creating intuitive user experiences. Streamlit provides several container elements that allow you to structure your content into logical sections, create multi-column layouts, and control the flow of information. These layout commands help transform a simple script into a polished application with professional presentation.


# Streamlit Layout and Containers Example
import streamlit as st
import pandas as pd
import numpy as np

st.title("Layout and Containers Demo")

# Sidebar
st.sidebar.header("Application Controls")
sidebar_slider = st.sidebar.slider("Select range", 0, 100, (25, 75))
sidebar_button = st.sidebar.button("Refresh Data")

# Columns
st.header("Multi-column Layout")
col1, col2, col3 = st.columns(3)

with col1:
    st.subheader("Column 1")
    st.write("This is column 1 content")
    st.metric("Revenue", "$4,251", "+12%")

with col2:
    st.subheader("Column 2")
    st.write("This is column 2 content")
    st.metric("Costs", "$1,823", "-8%")

with col3:
    st.subheader("Column 3")
    st.write("This is column 3 content")
    st.metric("Profit", "$2,428", "+24%")

# Uneven columns
st.header("Uneven Columns")
col1, col2 = st.columns([3, 1])
with col1:
    st.write("This is a wider column (3 units)")
with col2:
    st.write("This is a narrower column (1 unit)")

# Containers
st.header("Containers")

# Regular container
with st.container():
    st.write("This is inside a container")
    st.bar_chart(np.random.randn(20, 3))

# Expander
with st.expander("Expand to see details"):
    st.write("This content is hidden by default")
    st.line_chart(np.random.randn(20, 3))

# Tabs
st.header("Tabs")
tab1, tab2, tab3 = st.tabs(["Historical Data", "Forecast", "Analysis"])

with tab1:
    st.header("Historical Data")
    st.write("This is the historical data view")
    chart_data = pd.DataFrame(np.random.randn(20, 3), columns=["A", "B", "C"])
    st.line_chart(chart_data)

with tab2:
    st.header("Forecast")
    st.write("This is the forecast view")
    forecast_data = pd.DataFrame(np.random.randn(20, 3) + 0.5, columns=["A", "B", "C"])
    st.area_chart(forecast_data)

with tab3:
    st.header("Analysis")
    st.write("This is the analysis view")
    st.dataframe(pd.DataFrame({
        "Metric": ["Mean", "Median", "Std Dev"],
        "Value": [0.5, 0.45, 0.98]
    }))
    

Streamlit: State Management and Session State

One of the challenges in Streamlit's execution model is preserving state between re-runs of your script. To address this, Streamlit introduced the Session State API, which provides a way to persist data across reruns. This feature enables more complex applications with features like multi-page forms, game state, authentication flows, and other scenarios requiring persistent memory between interactions.


# Streamlit State Management Example
import streamlit as st
import pandas as pd
import numpy as np

st.title("Session State Demo")

# Initialize session state variables if they don't exist
if 'counter' not in st.session_state:
    st.session_state.counter = 0

if 'messages' not in st.session_state:
    st.session_state.messages = []

if 'data' not in st.session_state:
    st.session_state.data = pd.DataFrame(
        np.random.randn(5, 3),
        columns=['A', 'B', 'C']
    )

# Functions that modify session state
def increment_counter():
    st.session_state.counter += 1

def add_message():
    if st.session_state.new_message:  # Check if message isn't empty
        st.session_state.messages.append(st.session_state.new_message)
        st.session_state.new_message = ""  # Clear the input

def reset_all():
    st.session_state.counter = 0
    st.session_state.messages = []
    st.session_state.data = pd.DataFrame(
        np.random.randn(5, 3),
        columns=['A', 'B', 'C']
    )

# Display current state
st.header("Current Session State")
st.write(f"Counter value: {st.session_state.counter}")

# Buttons to modify state
st.button("Increment Counter", on_click=increment_counter)

# Text input with callback
st.text_input(
    "Add a message",
    key="new_message",
    on_change=add_message
)

# Display messages
st.subheader("Message History")
if st.session_state.messages:
    for i, message in enumerate(st.session_state.messages):
        st.text(f"{i+1}. {message}")
else:
    st.write("No messages yet.")

# Show dataframe from session state
st.subheader("Persistent DataFrame")
st.dataframe(st.session_state.data)

# Form example
with st.form(key="data_form"):
    st.write("Add a row to the DataFrame")
    col1, col2, col3 = st.columns(3)
    new_a = col1.number_input("A value", format="%.2f")
    new_b = col2.number_input("B value", format="%.2f")
    new_c = col3.number_input("C value", format="%.2f")
    
    submit_button = st.form_submit_button("Add Row")
    if submit_button:
        new_row = pd.DataFrame([[new_a, new_b, new_c]], columns=['A', 'B', 'C'])
        st.session_state.data = pd.concat([st.session_state.data, new_row], ignore_index=True)
        st.success("Row added successfully!")

# Reset everything
st.button("Reset All State", on_click=reset_all)
    

Streamlit: Advanced Features and Customization

Beyond the core functionality, Streamlit offers several advanced features for customizing your application's behavior and appearance. These include page configuration settings, caching mechanisms for performance optimization, and theming options. Additionally, Streamlit's component system allows for extending the framework with custom elements, enabling integration with specialized JavaScript libraries and interactive widgets not provided by the core platform.


# Streamlit Advanced Features Example
import streamlit as st
import pandas as pd
import numpy as np
import time

# Configure the page
st.set_page_config(
    page_title="Advanced Streamlit Features",
    page_icon="πŸ“Š",
    layout="wide",
    initial_sidebar_state="expanded",
    menu_items={
        'Get Help': 'https://docs.streamlit.io',
        'Report a bug': "https://github.com/streamlit/streamlit/issues",
        'About': "# This is a demo of advanced Streamlit features."
    }
)

# Custom CSS
st.markdown("""

""", unsafe_allow_html=True)

st.title("Advanced Streamlit Features")

# Performance optimization with caching
@st.cache_data
def load_large_dataset():
    # Simulate loading a large dataset
    time.sleep(2)  # Simulating long operation
    return pd.DataFrame(
        np.random.randn(1000, 5),
        columns=["A", "B", "C", "D", "E"]
    )

# Use the cached function
st.subheader("Cached Data Loading")
with st.spinner("Loading data... (only slow the first time)"):
    data = load_large_dataset()
    st.success("Data loaded successfully!")
    st.dataframe(data.head())

# Progress bar example
st.subheader("Progress Bar")
progress_text = "Operation in progress. Please wait..."
my_bar = st.progress(0, text=progress_text)

for percent_complete in range(100):
    time.sleep(0.01)  # Simulate operation that takes time
    my_bar.progress(percent_complete + 1, text=f"{progress_text} {percent_complete+1}%")

st.success("Operation completed!")

# Spinner example with time-consuming computation
st.subheader("Spinner Example")
with st.spinner("Computing complex model..."):
    # Simulate long computation
    time.sleep(3)
    result = np.random.randn(1) * 100
    st.write(f"Model result: {result[0]:.2f}")

# Balloons and snow celebration effects
st.subheader("Celebration Effects")
if st.button("Celebrate with Balloons"):
    st.balloons()

if st.button("Celebrate with Snow"):
    st.snow()

# Error handling example
st.subheader("Error Handling")
try:
    # Simulate an error
    if st.button("Trigger Error"):
        1/0
except Exception as e:
    st.error(f"An error occurred: {str(e)}")
    st.exception(e)  # Display the full traceback

# Display JSON with syntax highlighting
st.subheader("JSON Display")
st.json({
    "name": "Streamlit",
    "features": ["Easy to use", "Fast prototyping", "Great for data apps"],
    "versions": {
        "current": "1.x",
        "previous": "0.x"
    }
})

# Custom component example (hypothetical)
st.subheader("Custom Components")
st.write("""
Streamlit can be extended with custom components.
This would normally render a JavaScript-based custom component.
""")

# Download button for CSV
st.subheader("File Download")
csv = data.to_csv(index=False)
st.download_button(
    label="Download data as CSV",
    data=csv,
    file_name='sample_data.csv',
    mime='text/csv',
)
    

Streamlit: Multi-Page Applications

As applications grow in complexity, organizing content across multiple pages becomes essential for maintaining a clean, intuitive user experience. Streamlit's multi-page application framework provides a simple way to structure complex applications into separate pages, each with its own Python script. This architecture enables modular development, improved organization, and a more app-like experience for end users navigating between different sections of your application.


# File structure for multi-page Streamlit app:
# πŸ“ my_streamlit_app/
# β”œβ”€β”€ πŸ“„ requirements.txt
# β”œβ”€β”€ πŸ“ pages/
# β”‚   β”œβ”€β”€ πŸ“„ 01_Data_Explorer.py
# β”‚   β”œβ”€β”€ πŸ“„ 02_Model_Training.py
# β”‚   β”œβ”€β”€ πŸ“„ 03_Predictions.py
# β”‚   └── πŸ“„ 04_About.py
# └── πŸ“„ Home.py  (main app entry point)

# Example: Home.py (Main entry page)
import streamlit as st

st.set_page_config(
    page_title="Multi-Page Streamlit App",
    page_icon="🏠",
    layout="wide"
)

st.title("Welcome to My Multi-Page Streamlit App")
st.sidebar.success("Select a page above.")

st.markdown("""
    This is a multi-page Streamlit application demonstrating how to organize
    complex data applications into multiple pages.
    
    πŸ‘ˆ **Select a page from the sidebar** to explore different features:
    
    * **Data Explorer**: Visualize and analyze the dataset
    * **Model Training**: Configure and train machine learning models
    * **Predictions**: Make predictions with trained models
    * **About**: Learn more about this application
""")

# Display a welcome image
st.image("https://www.example.com/welcome_image.jpg", use_column_width=True)

# Show some sample statistics
st.subheader("Quick Stats")
col1, col2, col3 = st.columns(3)
col1.metric("Dataset Size", "1.2 GB", "2.1%")
col2.metric("Models Available", "4", "+1")
col3.metric("Prediction Accuracy", "92.7%", "+3.4%")

# Example: pages/01_Data_Explorer.py
import streamlit as st
import pandas as pd
import plotly.express as px

st.set_page_config(
    page_title="Data Explorer",
    page_icon="πŸ“Š",
    layout="wide"
)

st.title("Data Explorer")
st.sidebar.header("Data Explorer Settings")

# Simulate loading data
@st.cache_data
def load_data():
    # In a real application, this would load your actual data
    df = pd.DataFrame({
        'Category': ['A', 'B', 'C', 'D', 'E'] * 20,
        'Values': np.random.randn(100),
        'Group': np.random.choice(['Group 1', 'Group 2'], 100)
    })
    return df

df = load_data()

# Sidebar controls
selected_categories = st.sidebar.multiselect(
    "Select Categories",
    options=df['Category'].unique(),
    default=df['Category'].unique()
)

view_type = st.sidebar.radio(
    "View Type",
    ["Table", "Chart"]
)

# Filter data based on selection
filtered_df = df[df['Category'].isin(selected_categories)]

# Display based on view type
if view_type == "Table":
    st.subheader("Data Table View")
    st.dataframe(filtered_df)
else:
    st.subheader("Data Visualization")
    chart_type = st.sidebar.selectbox(
        "Chart Type",
        ["Bar Chart", "Scatter Plot", "Histogram", "Box Plot"]
    )
    
    if chart_type == "Bar Chart":
        fig = px.bar(
            filtered_df.groupby('Category').mean().reset_index(),
            x='Category', 
            y='Values',
            color='Category',
            title="Average Values by Category"
        )
        st.plotly_chart(fig, use_container_width=True)
    
    elif chart_type == "Scatter Plot":
        fig = px.scatter(
            filtered_df,
            x='Category',
            y='Values',
            color='Group',
            title="Values by Category and Group"
        )
        st.plotly_chart(fig, use_container_width=True)
    
    elif chart_type == "Histogram":
        fig = px.histogram(
            filtered_df,
            x='Values',
            color='Category',
            title="Distribution of Values"
        )
        st.plotly_chart(fig, use_container_width=True)
    
    elif chart_type == "Box Plot":
        fig = px.box(
            filtered_df,
            x='Category',
            y='Values',
            color='Group',
            title="Value Distribution by Category and Group"
        )
        st.plotly_chart(fig, use_container_width=True)

# Download the filtered data
st.sidebar.download_button(
    "Download Filtered Data",
    filtered_df.to_csv(index=False),
    "filtered_data.csv",
    "text/csv"
)
    

Streamlit: Deployment Options

Once you've developed your Streamlit application, sharing it with others is the next step. Streamlit offers multiple deployment options ranging from their managed hosting service, Streamlit Cloud, to self-hosting on various cloud platforms. The deployment choice depends on factors such as required resources, expected traffic, security requirements, and budget constraints. Regardless of the chosen platform, Streamlit applications maintain their functionality across different deployment environments with minimal configuration changes.


# Example Dockerfile for Streamlit application
FROM python:3.9-slim

WORKDIR /app

# Copy requirements and install dependencies
COPY requirements.txt .
RUN pip install -r requirements.txt

# Copy application files
COPY . .

# Expose port for the Streamlit app
EXPOSE 8501

# Command to run the application
CMD ["streamlit", "run", "Home.py", "--server.port=8501", "--server.address=0.0.0.0"]
    

Streamlit: Best Practices and Performance Optimization

As your Streamlit applications grow in complexity, following best practices becomes essential for maintaining performance and usability. The reactive execution model, while powerful, can lead to inefficient recomputation if not properly managed. Techniques like proper caching, state management, and code organization can significantly improve the user experience and reduce resource usage. Additionally, thoughtful UI design principles should be applied to create intuitive, responsive interfaces that effectively communicate insights from your data.

"The biggest revelation in my Streamlit journey was understanding the execution modelβ€”every interaction reloads the entire script. Once I embraced strategic caching and session state management, my applications became dramatically more responsive and professional."

Streamlit: Command Reference Quick Guide

For quick reference, here's a comprehensive list of the most commonly used Streamlit commands, organized by category. This guide serves as a cheat sheet for both beginners and experienced developers looking to quickly implement specific functionality in their applications.

Text Elements

  • st.title("Text") - Display page title
  • st.header("Text") - Display section header
  • st.subheader("Text") - Display subsection header
  • st.text("Text") - Display fixed-width text
  • st.markdown("**Text**") - Display formatted Markdown
  • st.caption("Text") - Display small text
  • st.code("code", language="python") - Display formatted code
  • st.latex(r"\frac{a}{b}") - Display mathematical expressions
  • st.write(object) - Display anything (text, data, figures)

Data Display Elements

  • st.dataframe(df) - Display interactive dataframe
  • st.table(df) - Display static table
  • st.json(dict) - Display JSON object
  • st.metric("Label", value, delta) - Display metric with optional delta

Chart Elements

  • st.line_chart(data) - Display line chart
  • st.area_chart(data) - Display area chart
  • st.bar_chart(data) - Display bar chart
  • st.pyplot(fig) - Display matplotlib figure
  • st.altair_chart(chart) - Display Altair chart
  • st.plotly_chart(fig) - Display
s