When writing Python, some data analysis scripts are quite convenient to run, but sharing them with others or creating an interactive interface can become troublesome. The traditional web development process is tedious and lengthy: HTML, CSS, JavaScript, and a bunch of frameworks can be overwhelming.Streamlit perfectly solves this problem by transforming Python scripts into beautiful web applications with minimal code. How simple is it? Just write a function, run a command, and the page is generated instantly.
1. Installation and Quick Experience
First, install Streamlit, then experience its magic with a short piece of code.
Install Streamlit
pip install streamlit
Create a Simple App
Pick any folder, create a new app.py
file, and write the following lines of code:
import streamlit as st
st.title("Hello, Streamlit!")
st.write("This is a simple Streamlit app.")
After saving, run it in the terminal:
streamlit run app.py
Your browser will automatically open, and you will see a clean page displaying “Hello, Streamlit!”. No server configuration is needed, and no frontend code is required; the page is generated like magic.
2. Common Page Elements
Streamlit provides many convenient components for displaying text, images, charts, and even interactive controls. Let’s take a look at some commonly used ones.
Titles and Text
Page titles, paragraphs, and code blocks are the basics of a page.
st.title("Title: Quick Start with Streamlit")
st.header("This is a small title")
st.subheader("This is an even smaller title")
st.write("Normal text using `st.write`, supports Markdown syntax.")
st.code("x = 42 # This is a code block")
These codes will generate various styles of text on the page. st.write
is the most versatile function and can display almost any content.
Images and Media
Streamlit also supports images, audio, and video, making it particularly easy to display.
from PIL import Image
image = Image.open("example.jpg")
st.image(image, caption="This is an image", use_column_width=True)
st.audio("example.mp3")
st.video("example.mp4")
Images can be opened using Pillow
, and audio and video can be referenced directly by file path.
Chart Display
Data analysis often requires plotting, and Streamlit supports many mainstream visualization libraries like Matplotlib, Seaborn, Plotly, etc.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
fig, ax = plt.subplots()
ax.plot(x, y)
st.pyplot(fig)
The code above directly embeds a Matplotlib chart into the page, providing a very smooth effect.
Tip: Streamlit also has built-in simple chart methods like st.line_chart
and st.bar_chart
, which are faster to use than Matplotlib.
3. Interactive Components
Streamlit’s interactive components are its highlights, allowing users to input data, select options, and update the page in real-time.
Input Boxes and Buttons
You can use input boxes and buttons to obtain user input, which is very convenient.
name = st.text_input("What is your name?")
if st.button("Submit"):
st.write(f"Hello, {name}!")
After the user inputs their name and clicks the “Submit” button, the page will display a greeting message.
Sliders and Select Boxes
Sliders and select boxes are suitable for adjusting parameters.
age = st.slider("Select your age", 0, 100, 25)
st.write(f"Your selected age is: {age}")
option = st.selectbox("Choose an option", ["Option 1", "Option 2", "Option 3"])
st.write(f"You selected: {option}")
Sliders can be used to select a value within a range, while select boxes allow for selecting an option, dynamically updating the page based on user selection.
Multi-select and Checkboxes
If you need to select multiple options at once, you can use multi-select or checkboxes.
choices = st.multiselect("Select your favorite fruits", ["Apple", "Banana", "Orange", "Grape"])
st.write(f"You selected: {', '.join(choices)}")
agree = st.checkbox("I agree to the terms")
if agree:
st.write("You agreed to the terms.")
4. Dynamic Updates and State Management
Another feature of Streamlit is that its code is “scripted,” meaning that every interaction re-runs the entire script. This approach is simple and intuitive, but there are some considerations.
Dynamic Updates
For example, if you want to calculate a value in real-time based on user input, you can directly write the logic in the code.
number = st.number_input("Enter a number")
st.write(f"The square of {number} is: {number ** 2}")
As the user inputs a number, the page will update the square result in real-time.
State Management
If you need to maintain the user’s operation state, you can use st.session_state
, which acts like a global dictionary.
if "count" not in st.session_state:
st.session_state.count = 0
if st.button("Click me to add 1"):
st.session_state.count += 1
st.write(f"Current count: {st.session_state.count}")
Clicking the button will increase the count, and the state will be preserved when the page refreshes.
5. Deployment and Sharing
Deploying Streamlit applications is also very simple; you can use the cloud service provided by the Streamlit community or set up your own server.
Using Streamlit Cloud
Upload the code to GitHub, log in to Streamlit Cloud, bind the repository, and you can deploy with one click, completely free, and it even supports sharing links.
Self-deployment
If you have your own server, you can run the application with the following command:
streamlit run app.py --server.port 8501
Then use Nginx or other reverse proxy tools to publish the application to the public network.
6. Common Issues and Debugging Tips
When using Streamlit, there are some common issues to be aware of.
Page Refresh
Streamlit scripts re-run after every interaction. If some code is time-consuming, you can cache results using st.cache
:
@st.cache
def expensive_computation(x):
return x ** 2
st.write(expensive_computation(42))
Resetting Controls
If you need to reset the state of controls after certain operations, you can use st.session_state.clear()
to clear the state.
Streamlit is a tool that makes developing data applications simple and fun. It can build beautiful web interfaces with minimal code, making it especially suitable for data analysts and engineers to quickly share their results. Try writing a few small applications with it, and you’ll find that developing web applications can be this easy!