Getting Started with Streamlit

Here is a basic tutorial on how to get started with Streamlit, a popular framework for building web apps with Python:

1. Install Streamlit

To start using Streamlit, you need to install it first. Run the following command in your terminal or prompt:

pip install streamlit

2. Create a Simple App

Create a new Python file, for example, app.py, and add the following code:

import streamlit as st

# Title of the web app
st.title("Welcome to Streamlit")

# Header
st.header("This is a simple app")

# Text input
name = st.text_input("Enter your name:")

# Slider
age = st.slider("Select your age:", 0, 100)

# Display user input
if st.button("Submit"):
    st.write(f"Hello {name}, you are {age} years old!")

3. Run the App

To run your Streamlit app, use the following command:

streamlit run app.py

This will open the app in your default web browser at http://localhost:8501.

4. Basic Widgets

Streamlit provides a variety of widgets for user interaction. Here are some common ones:

4.1. Text Input

name = st.text_input("Enter your name:")
st.write(f"Your name is {name}")

4.2. Slider

age = st.slider("Select your age:", 0, 100)
st.write(f"You are {age} years old")

4.3. Button

if st.button("Click me"):
    st.write("Button clicked!")

4.4. Checkbox

if st.checkbox("Show more info"):
    st.write("Here is some more information...")

4.5. Select Box

option = st.selectbox("Select a number:", [1, 2, 3, 4, 5])
st.write(f"You selected {option}")

4.6. File Uploader

uploaded_file = st.file_uploader("Choose a file")
if uploaded_file is not None:
    st.write("File uploaded successfully!")

5. Displaying Data

You can display data in the form of tables, charts, and even code:

5.1. Displaying DataFrames

import pandas as pd

data = {'Name': ['John', 'Anna', 'Peter'],
        'Age': [28, 24, 35]}
df = pd.DataFrame(data)
st.dataframe(df)

5.2. Plotting Charts

Streamlit supports popular plotting libraries such as Matplotlib, Plotly, and Altair:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot([1, 2, 3], [10, 20, 30])
st.pyplot(fig)

6. Layouts

You can arrange elements in your Streamlit app using columns or containers:

6.1. Columns

col1, col2 = st.columns(2)

col1.write("This is column 1")
col2.write("This is column 2")

6.2. Containers

with st.container():
    st.write("This is inside a container")

7. Deploying the App

Streamlit can be deployed on services like Streamlit Cloud, Heroku, or AWS.

To deploy on Streamlit Cloud, follow these steps:

  1. Push your code to a public GitHub repository.
  2. Go to Streamlit Cloud.
  3. Sign in and connect your GitHub account.
  4. Select the repository and deploy the app.

This is a basic overview of how to get started with Streamlit. You can extend this to build complex data dashboards, machine learning model interfaces, or interactive web applications.