Welcome to Module 2!
Time to take our Streamlit app to the next level! In Module 1 we covered the basics, but to build applications that feel truly professional, we need structure and real-world data.
Today we’ll learn to separate controls from main content using the sidebar, upload files (real CSV files), and implement a multi-page routing and navigation system.
The Sidebar: Your Dashboard’s Side Panel
Have you ever seen a control panel with all the filters piled at the top of the content? It turns into chaos quickly! The golden rule for building good interfaces in Streamlit is to separate controls and settings (Sidebar) from visualizations and data (Center).
There are two ways to send widgets to the sidebar:
1. Using the direct prefix (Ideal for 1 or 2 controls):
st.sidebar.title("Settings")
st.sidebar.slider("Year", 2018, 2024) 2. Using the with block (Recommended):
It’s much cleaner and easier to read as the application grows.
with st.sidebar:
st.title("Settings")
st.selectbox("Country", ["USA", "China", "Ecuador"])
st.button("Apply Filters") Options and Multiple Selections
Two essential widgets for letting the user choose options are selectbox and radio. When should you use each?
st.selectbox()(Dropdown list): Takes up very little vertical space. Ideal for 5 or more options (for example, a list of 50 countries or hundreds of categories).option = st.selectbox("Choose a country", ["USA", "China", "Ecuador"], index=0)st.radio()(Radio buttons): Shows all options on screen at once. Use it when you have few options (2 to 4) and want the user to clearly see all alternatives without extra clicks. Perfect for navigation menus in a single file!view = st.radio("Navigate to:", [" Data", " Chart"], horizontal=False)
Loading Real Data: Pandas and the File Uploader
Every data analysis application starts with data. With Streamlit, we can let the user upload a CSV file directly from their computer.
For this, we use st.file_uploader().
Critical Rule: This widget returns None if the user hasn’t uploaded anything yet. Trying to read an empty DataFrame will crash your app with an ugly error. You MUST always check whether the file exists before processing it.
import pandas as pd
file = st.sidebar.file_uploader("Upload your CSV", type=["csv"])
if file is not None:
# Only process this if the user uploaded the file
df = pd.read_csv(file)
# Render the table with all the automatic sorting features
st.dataframe(df, use_container_width=True, hide_index=True)
else:
st.info("Upload a file to get started") The Multi-page Navigation Menu
As your app grows, you’ll want to split it into multiple sections. You have two main strategies:
Option A: A Single File (Ideal for Small Demos)
Use the variable from an st.radio() inside the sidebar to conditionally render different parts of the script.
with st.sidebar:
page = st.radio("Go to:", [" Data", " Chart"])
if page == " Data":
st.title("Data Table")
# Code to show st.dataframe...
elif page == " Chart":
st.title("Interactive Chart")
# Code to show charts... Option B: Separate Files (Ideal for Large Projects)
Create a folder called pages/ next to your main file. Add your pages with numeric prefixes to control their order. Streamlit will automatically detect the folder and create the menu in the sidebar with no extra code.
File structure:
my-project/
├── main_file.py ← Your app's home page
├── pages/
│ ├── 1_Data.py ← Appears as "Data" in the menu
│ └── 2_Chart.py ← Appears as "Chart" in the menu
└── data.csv Your first chart with Plotly Express
Streamlit integrates perfectly with Plotly. Unlike Matplotlib (which generates static images), Plotly gives you interactive tools directly in the browser: hover over the data, zoom, and panning—with no additional code.
import plotly.express as px
# Assuming we already have df loaded...
fig = px.bar(
df,
x="Country",
y="Tariff",
title="Tariffs by Country",
color="Tariff",
color_continuous_scale="Reds"
)
# Magic! Render the chart in Streamlit
st.plotly_chart(fig, use_container_width=True) Managing flow with st.stop() and st.set_page_config()
To build robust apps, two essential commands:
st.set_page_config(): Configures the title and favicon of your browser tab, as well as the layout (“wide” or “centered”). It must be the first Streamlit command you call in the entire script.st.stop(): Stops script execution gracefully and silently. It’s a perfect “lifesaver” when data is missing.
st.set_page_config(page_title="My Dashboard", page_icon="", layout="wide")
file = st.sidebar.file_uploader("CSV")
if file is None:
st.info("Please upload the CSV file.")
st.stop() # Execution stops here. No ugly errors.
# If the script keeps running, we know the file exists
df = pd.read_csv(file) You now have the tools to create formidable multi-page dashboards with your own interactive data! In Module 3, we’ll learn how to store information in memory, organize layouts professionally with columns and tabs, and create caches so our databases don’t suffer on every reload.
