Frontend Development 11 min read

Getting Started with Streamlit: Installation, Core Components, and Sample Projects

This tutorial introduces Streamlit—a Python library for building interactive web apps—covering installation, layout, widgets, data caching, charting, and example projects such as dynamic data exploration and a face‑detection demo, all with complete code snippets.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Getting Started with Streamlit: Installation, Core Components, and Sample Projects

1. Streamlit

Streamlit is a Python library that lets you create web applications to dynamically showcase machine‑learning projects without writing any HTML, CSS, or JavaScript.

Advantages

You can build a web app using pure Python.

Provides common UI components: text boxes, buttons, radio buttons, checkboxes, select boxes, multimedia (images, video) and file upload.

Typical use cases

Interactive data exploration.

Dynamic presentation of machine‑learning results (similar to Jupyter notebooks).

https://github.com/streamlit/streamlit

2. Installation

<code>pip install streamlit</code>
<code>streamlit hello
# start web app
# streamlit run [filename]
streamlit run app.py
# You can now view your Streamlit app in your browser.
# Local URL: http://localhost:8501</code>

3. Basic Component Overview

3.1 Layout

Streamlit offers a simple two‑column layout. Use st.sidebar to add a sidebar that can act as a menu or control panel; the main area renders top‑down according to the script order.

<code>import streamlit as st
import numpy as np
import time
import pandas as pd
import datetime

st.sidebar.title('Menu Sidebar')
add_selectbox = st.sidebar.selectbox(
    "This is a dropdown, please choose?",
    ("1", "Home 2", "Mobile 2")
)
st.title('Streamlit Machine Learning Web App')
</code>

3.2 Text

Streamlit supports various text‑display commands and markdown syntax.

<code>st.header('1. Text Display')
st.markdown('Streamlit is **_really_ cool**.')
st.text('This is some text.')
st.subheader('This is a subheader')
st.write('st.write can render many things')
st.warning('This is a warning')
</code>

3.3 Form Controls

Rich form widgets are available; the function call defines the control and returns a value indicating whether it was triggered.

<code># button
if st.button('Say hello'):
    st.write('Why hello there')

# radio
genre = st.radio('Choose your favorite?', ('Comedy', 'Drama', 'Documentary'))
st.write('You selected:', genre)

# checkbox
agree = st.checkbox('I agree')
if agree:
    st.write('Thank you for agreeing')

# selectbox
option = st.selectbox('Preferred contact method?', ('Email', 'Home phone', 'Mobile phone'))
st.write('You chose:', option)

# multiselect
options = st.multiselect('What are your favorite colors', ['Green', 'Yellow', 'Red', 'Blue'], ['Yellow', 'Red'])
st.write('You selected:', options)

# slider
values = st.slider('Select a range of values', 0.0, 100.0, (25.0, 75.0))
st.write('Values:', values)

# text input
title = st.text_input('Movie title', 'Life of Brian')
st.write('Current title is', title)

# text area
txt = st.text_area('Text to analyze', '''It was the best of times, it was the worst of times,...''')

# date and time
d = st.date_input('Birthday', datetime.date(2019, 7, 6))
st.write('Your birthday is:', d)

t = st.time_input('Alarm', datetime.time(8, 45))
st.write('Alarm set to:', t)

# file uploader
uploaded_file = st.file_uploader('Choose a CSV file', type='csv')
if uploaded_file is not None:
    data = pd.read_csv(uploaded_file)
    st.write(data)
</code>

3.4 Images

Display images using st.image , which works with any image array (e.g., from OpenCV).

<code>import cv2
img = cv2.imread('sunrise.jpg')
st.image(img[..., ::-1], caption='Sunrise by the mountains', use_column_width=True)
</code>

3.5 Charts

Streamlit can render pandas DataFrames directly as line, area, and bar charts, and also supports Matplotlib figures.

<code>@st.cache(persist=True)
def get_data():
    df = pd.DataFrame(np.random.randn(200, 3), columns=['a', 'b', 'c'])
    return df

df = get_data()
st.dataframe(df)
st.line_chart(df)
st.area_chart(df)
st.bar_chart(df)

# Matplotlib example
plt.plot(df.a, df.b)
st.pyplot()
</code>

3.6 Caching

Use the st.cache decorator on functions to avoid re‑loading data on every rerun.

<code>@st.cache(persist=True)
def get_data():
    df = pd.DataFrame(np.random.randn(200, 3), columns=['a', 'b', 'c'])
    return df
</code>

4. Dynamic Data Demo

<code>import streamlit as st
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import datetime

st.sidebar.title('Select filter conditions')
time = st.sidebar.time_input('Greater than time', datetime.time(1, 0))
values = st.sidebar.slider('Speed', 0.0, 200.0, (25.0, 75.0))

st.title('Data Exploration')
@st.cache(persist=True)
def get_data():
    file = './7000.csv'
    return pd.read_csv(file, header=0)

data = get_data()
display_data = data[data['time'] > str(time)]
display_data = display_data[(display_data['speed'] > values[0]) & (display_data['speed'] < values[1])]
st.line_chart(display_data[['direction', 'speed']])
</code>

5. Machine‑Vision Project Demo

This example uses a face‑detection model (MTCNN from the facenet project) to upload an image, detect faces, and draw bounding boxes.

<code>import streamlit as st
import numpy as np
import matplotlib.pyplot as plt
import time, pandas as pd, datetime, cv2, io
from PIL import Image
from face_detect.mtcnn_tf import MTCNN

st.sidebar.title('Upload a photo to start detection')
uploaded_file = st.sidebar.file_uploader('', type='jpg')

st.title('Face Detection')
@st.cache()
def init_model():
    return MTCNN()

detect = init_model()
if uploaded_file is not None:
    data = np.array(Image.open(io.BytesIO(uploaded_file.read())))
    _, bboxs, _, _ = detect.run(data, detect_multiple_faces=True, margin=0)
    for idx, landmark in enumerate([]):  # placeholder for landmarks
        bbox = bboxs[idx]
        cv2.rectangle(data, (bbox[1], bbox[0]), (bbox[3], bbox[2]), (0, 2255, 0), 2)
    st.image(data, caption='image', use_column_width=False)
</code>

6. Summary

Remember to cache data with @st.cache() .

Streamlit can render Matplotlib charts.

It provides attractive form controls whose return values indicate user interaction.

Markdown rendering is supported.

Official demos with more complex use‑cases are available at the Streamlit GitHub repository.

machine learningPythonTutorialData VisualizationWeb AppStreamlit
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.