Streamlit: A Fast Python Framework for Web Development
Hi, I’m Mumu. Today, let’s talk about Streamlit, which is an amazing Python framework that allows you to quickly build websites. In simple terms, as long as you know a bit of Python, you can easily create beautiful and practical web applications with Streamlit, without having to learn complex front-end knowledge. Let’s dive deeper into it.
What is Streamlit
Streamlit is a Python library that allows you to quickly build interactive web applications using Python. In the past, to create a webpage, you might have to learn front-end knowledge like HTML, CSS, and JavaScript, and deal with front-end and back-end interactions, which is quite troublesome. But with Streamlit, you only need to write Python code, and it will help you turn that code into a webpage.
Let me give you a simple example. We create a new Python file, let’s call it app.py
, and then write the following code in it:
import streamlit as st
st.title('My First Streamlit App')
st.write('Welcome to using Streamlit for quick web development!')
Code Explanation
-
import streamlit as st
: This line imports the Streamlit library and gives it a short namest
, so we will usest
to call various functions of Streamlit in the future. -
st.title('My First Streamlit App')
: This line of code displays a title on the webpage, and the title content is the text inside the parentheses. -
st.write('Welcome to using Streamlit for quick web development!')
: This line of code displays a piece of text on the webpage.
Run the Code
In the terminal, switch to the directory where the app.py
file is located, and then run this command:
streamlit run app.py
After running, Streamlit will automatically open a browser window displaying the webpage you wrote. You will see a simple webpage with a title and welcome text.
Tip: Before running the streamlit run app.py
command, make sure you have installed the Streamlit library. You can install it using pip install streamlit
.
Using Basic Components
Streamlit provides many components that can make your webpage richer and more interesting. Below are a few commonly used components.
Button
The button component allows users to interact with your webpage. For example, in the following case, clicking the button will display a greeting message.
import streamlit as st
if st.button('Click Me'):
st.write('You clicked the button, welcome!')
Code Explanation
-
if st.button('Click Me'):
:st.button
creates a button, and the text displayed on the button is in the parentheses. This line means that if the user clicks this button, the indented code below will execute. -
st.write('You clicked the button, welcome!')
: If the button is clicked, this sentence will be displayed on the webpage.
Text Input
The text input box allows users to enter text, and we can retrieve and process the content entered by users. Here’s an example:
import streamlit as st
name = st.text_input('Please enter your name')
if name:
st.write(f'Hello, {name}! Welcome to my webpage.')
Code Explanation
-
name = st.text_input('Please enter your name')
: This line creates a text input box prompting the user to input their name, and the content entered by the user is assigned to the variablename
. -
if name:
: If thename
variable has a value, meaning the user has entered content, the following code will execute. -
st.write(f'Hello, {name}! Welcome to my webpage.')
: This inserts the user’s name into the greeting and displays it on the webpage.
Selectbox
The selectbox allows users to choose one option from multiple choices. See the example below:
import streamlit as st
option = st.selectbox('Please select your favorite fruit', ('Apple', 'Banana', 'Orange'))
st.write('The fruit you selected is:', option)
Code Explanation
-
option = st.selectbox('Please select your favorite fruit', ('Apple', 'Banana', 'Orange'))
: This line creates a selectbox prompting the user to choose their favorite fruit, with the options being Apple, Banana, and Orange. The value selected by the user will be assigned to the variableoption
. -
st.write('The fruit you selected is:', option)
: This displays the fruit selected by the user on the webpage.
Applications of Streamlit in Real Scenarios
Streamlit can be used in many scenarios, such as data visualization, machine learning model demonstrations, etc. Below is an example of data visualization.
Data Visualization
We will use Streamlit along with the pandas
and matplotlib
libraries to draw a simple line chart. Let’s say we have some simple data on monthly sales.
import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt
# Create sample data
data = { 'Month': ['January', 'February', 'March', 'April', 'May'], 'Sales': [1000, 1200, 1300, 1100, 1500] }
df = pd.DataFrame(data)
Draw the Line Chart
st.write('Monthly Sales Line Chart')
fig, ax = plt.subplots()
ax.plot(df['Month'], df['Sales'])
st.pyplot(fig)
Code Explanation
-
First, import the required libraries,
pandas
for data handling,matplotlib
for plotting, and Streamlit. -
Then create a dictionary
data
containing month and sales information, and convert the dictionary into a DataFramedf
usingpd.DataFrame
. -
Next, use
plt.subplots()
to create a figure and axis object, and useax.plot()
to draw the line chart. -
Finally, use
st.pyplot(fig)
to display the drawn chart on the webpage.
Exercises
-
Try adding a new button in
app.py
that displays an image you like when clicked (Hint: you can usest.image
). -
Expand the data visualization example by adding more data and drawing a bar chart.
Conclusion
Today we learned about Streamlit, a powerful Python framework. We understood its basic concepts, learned how to create simple web pages with it, and mastered the use of some common components, as well as its applications in real scenarios. Now you can try using Streamlit to build your own web applications!
Friends, that’s all for today’s Python learning journey! Remember to write some code, and feel free to ask me any questions in the comments section. I wish everyone a pleasant learning experience and continuous improvement in Python!