Interactivity in Streamlit Intermediate

Streamlit provides a rich set of input widgets that make your apps interactive. Every widget returns a value that you can use in your Python code. This lesson covers all major widgets, session state for persistent data, and forms for batch input.

Input Widgets

Python
import streamlit as st

# Button
if st.button("Click me", type="primary"):
    st.write("Button clicked!")

# Text input
name = st.text_input("Enter your name", placeholder="John Doe")

# Text area
bio = st.text_area("Tell us about yourself", height=150)

# Number input
age = st.number_input("Age", min_value=0, max_value=120, value=25)

# Slider
temperature = st.slider("Temperature", 0.0, 2.0, 0.7, step=0.1)

# Range slider
values = st.slider("Range", 0, 100, (25, 75))

# Selectbox (dropdown)
option = st.selectbox("Choose a model", ["GPT-4", "Claude", "Gemini"])

# Multi-select
colors = st.multiselect("Favorite colors", ["Red", "Green", "Blue"])

# Radio buttons
genre = st.radio("Genre", ["Comedy", "Drama", "Sci-Fi"], horizontal=True)

# Checkbox
agree = st.checkbox("I agree to the terms")

# Toggle
dark_mode = st.toggle("Dark mode")

# Date input
date = st.date_input("Select a date")

# Color picker
color = st.color_picker("Pick a color", "#00f900")

File Uploader

Python
# Single file upload
uploaded_file = st.file_uploader("Upload a CSV", type=["csv"])
if uploaded_file:
    df = pd.read_csv(uploaded_file)
    st.dataframe(df)

# Multiple file upload
files = st.file_uploader("Upload images", type=["png", "jpg"], accept_multiple_files=True)
for file in files:
    st.image(file, caption=file.name)

Session State

Session state persists values across script re-runs within a user session:

Python
# Initialize session state
if "counter" not in st.session_state:
    st.session_state.counter = 0

# Increment on button click
if st.button("Increment"):
    st.session_state.counter += 1

st.write(f"Counter: {st.session_state.counter}")

# Store chat messages
if "messages" not in st.session_state:
    st.session_state.messages = []

# Widget with session state key
st.text_input("Name", key="user_name")
# Access via: st.session_state.user_name

Forms

Forms batch multiple inputs together and only re-run the script when the form is submitted:

Python
with st.form("my_form"):
    st.write("Configure your model:")

    model = st.selectbox("Model", ["GPT-4", "Claude", "Gemini"])
    temperature = st.slider("Temperature", 0.0, 2.0, 0.7)
    max_tokens = st.number_input("Max Tokens", 100, 4000, 1000)
    prompt = st.text_area("Prompt")

    submitted = st.form_submit_button("Generate", type="primary")

    if submitted:
        st.write(f"Generating with {model} at temperature {temperature}...")

Chat Interface

Python
# Initialize chat history
if "messages" not in st.session_state:
    st.session_state.messages = []

# Display chat history
for msg in st.session_state.messages:
    with st.chat_message(msg["role"]):
        st.write(msg["content"])

# Chat input
if prompt := st.chat_input("Say something..."):
    st.session_state.messages.append({"role": "user", "content": prompt})
    with st.chat_message("user"):
        st.write(prompt)

    # Generate response (replace with actual LLM call)
    response = f"Echo: {prompt}"
    st.session_state.messages.append({"role": "assistant", "content": response})
    with st.chat_message("assistant"):
        st.write(response)

Callbacks

Python
# Run a function when a widget value changes
def on_change():
    st.session_state.greeting = f"Hello, {st.session_state.name_input}!"

st.text_input("Name", key="name_input", on_change=on_change)

if "greeting" in st.session_state:
    st.write(st.session_state.greeting)
Forms vs Regular Widgets: Use forms when you have multiple related inputs that should be submitted together (like a configuration form). Use regular widgets when each input should trigger an immediate re-run (like a live filter).

Interactive Apps Built!

Your apps are now fully interactive. Next, learn how to deploy Streamlit apps to the cloud.

Next: Deployment →

Ready to Go Deeper?

Live instructor-led courses from our partners. Affiliate disclosure.