Building Your First Streamlit App: A Step-by-Step Tutorial
Introduction
In the previous article, we introduced Streamlit and discussed why it’s a fantastic choice for building interactive web applications with Python. Now, it’s time to roll up our sleeves and dive into the practical aspects of creating your first Streamlit app. By the end of this tutorial, you’ll have a functional Streamlit app that you can share with others.
Prerequisites
Before we get started, ensure you have Streamlit installed. You can install it using pip:
pip install streamlit
Creating a Simple Streamlit App
Let’s start by building a straightforward Streamlit app that displays a customizable message.
1. Import Streamlit: Begin by importing the Streamlit library at the top of your Python script.
import streamlit as st
2. Create the App Title: Set the title of your app using st.title()
st.title('My First Streamlit App')
3. Add Text: You can include text using st.write()
.
st.write('Welcome to my Streamlit app!')
Note:
st.write()
is one of the most important functions of streamlit. In later sections we will see why.
4. Display User Input: Let’s make it interactive by adding a text input widget that allows users to customize the displayed message.
user_input = st.text_input('Enter a custom message:', 'Hello, Streamlit!')
5. Display the Customized Message: Display the customized message using st.write()
.
st.write('Customized Message:', user_input)
Your complete script should look like this:
import streamlit as st
# Set the app title
st.title('My First Streamlit App')
# Add a welcome message
st.write('Welcome to my Streamlit app!')
# Create a text input
widgetuser_input = st.text_input('Enter a custom message:', 'Hello, Streamlit!')
# Display the customized message
st.write('Customized Message:', user_input)
Running Your Streamlit App
To run your Streamlit app, open your terminal or command prompt and navigate to the directory where your script is located. Then, execute the following command:
streamlit run your_script.py
Replace your_script.py
with the name of your Python script.
Interact with Your App
Once your app is running, you can interact with it directly in your web browser. Try entering different custom messages in the text input field and observe how the displayed message updates in real-time.
Conclusion
Congratulations! You’ve successfully created your first Streamlit app. In this tutorial, we covered the basics of setting up a Streamlit app, adding text and user input widgets, and displaying dynamic content. In future tutorials, we’ll explore more advanced features of Streamlit, such as data visualization, integrating external libraries, and deploying your apps for sharing with others. Stay tuned for more Streamlit adventures!