Basic Components in Streamlit
Streamlit offers a variety of components that allow you to create interactive and dynamic web applications with minimal code. Two fundamental components are Text Elements and Input Widgets. Understanding these components is essential for building effective Streamlit apps.
1. Text Elements
Text elements in Streamlit are used to display text content in your application. They include functions like st.title()
, st.header()
, st.subheader()
, and st.write()
. These functions help in structuring the text content and making it more readable.
Examples:
import streamlit as st st.title("Welcome to Streamlit") st.header("This is a header") st.subheader("This is a subheader") st.write("This is a general text element")
In this example, st.title()
is used to display a large title, st.header()
for a main heading, st.subheader()
for a subheading, and st.write()
for general text. These functions help in organizing the content and making it visually appealing.
2. Input Widgets
Input widgets in Streamlit allow users to interact with the application by providing input. Common widgets include st.text_input()
, st.number_input()
, st.checkbox()
, and st.selectbox()
. These widgets enable dynamic interaction and data collection from users.
Examples:
import streamlit as st user_input = st.text_input("Enter your name") st.write(f"Hello, {user_input}!") age = st.number_input("Enter your age", min_value=0, max_value=120) st.write(f"You are {age} years old.") agree = st.checkbox("Do you agree?") if agree: st.write("You agreed!") else: st.write("You did not agree.") option = st.selectbox("Choose an option", ["Option 1", "Option 2", "Option 3"]) st.write(f"You selected: {option}")
In this example, st.text_input()
collects a user's name, st.number_input()
collects their age, st.checkbox()
records their agreement, and st.selectbox()
allows them to choose from a list of options. These widgets make the application interactive and user-friendly.
By mastering these basic components, you can create engaging and functional Streamlit applications that effectively communicate information and gather user input.