Widgets — the controls of your app
Widgets are everything the user can touch: text boxes, buttons, sliders, dropdowns, checkboxes. Master six of them and you can build 90% of the apps in this course.
The Big Six
import streamlit as st
# 1. text_input — short text
name = st.text_input("Your name", placeholder="Type here...")
# 2. number_input — numbers only
age = st.number_input("Your age", min_value=0, max_value=120, value=18)
# 3. selectbox — pick one from a list
language = st.selectbox("Favorite language", ["Python", "Go", "Rust"])
# 4. slider — pick a number in a range
height = st.slider("Height (cm)", 100, 250, 170)
# 5. checkbox — on/off
agree = st.checkbox("I agree to the terms")
# 6. button — trigger an action
if st.button("Submit"):
st.write(f"{name}, {age}, likes {language}, is {height}cm, agreed: {agree}")
Every widget returns a value — that’s the mental model. The widget draws itself, collects the user’s choice, and hands it to your variable on every rerun.
Widget keys — the identity system
When you place the same widget twice, Streamlit can’t tell them apart unless you give each a unique key:
st.text_input("From", key="from_city")
st.text_input("To", key="to_city")
Rule of thumb: if two widgets ever confuse each other, give them keys. You’ll see keys everywhere in this course, especially inside loops.
Choosing the right widget
| If the user should… | Use |
|---|---|
| Type short text | text_input |
| Type paragraphs | text_area |
| Enter a number | number_input |
| Pick from 2–10 options | selectbox or radio |
| Pick a number in a range | slider |
| Turn something on/off | checkbox |
| Trigger an action | button |
Common Errors & Fixes
- Two widgets change together — they share state; give each a unique key.
- The button’s if never runs — buttons return True only on the click’s rerun; make sure your action code is indented inside the if.
- TypeError when doing math on a text_input — it returns a string; convert with int() or use number_input.
What to try next
Build a mini “student card” generator: name, age, and class inputs + a button that prints a formatted card using an f-string. Every widget above except the slider is in play.
Key takeaways
- • Every core widget and when to use it
- • Widget keys and why they matter
- • Reading values into Python variables