> ## Documentation Index
> Fetch the complete documentation index at: https://fastapi2day.codewithsiva.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Streamlit Widgets: Collecting and Handling User Input

> Learn how to use Streamlit buttons, text inputs, selectboxes, sliders, file uploaders, and date pickers to collect input from your users.

Widgets are the interactive building blocks of every Streamlit app. They let users provide data, make selections, upload files, and trigger actions — and because Streamlit reruns your script on every interaction, the rest of your app responds to widget values automatically. Each widget function returns the current value chosen by the user, which you can store in a variable and use anywhere in your Python logic. This page covers every major widget type with ready-to-use code examples.

## Buttons

A button triggers an action when clicked. The button function returns `True` for the single rerun that follows a click, then `False` again on all subsequent reruns.

```python theme={null}
import streamlit as st

if st.button("Generate Report"):
    st.write("Report generated successfully!")

# Disabled button
st.button("Submit", disabled=True)
```

## Text Input and Text Area

Use text fields for free-form user input. `text_input` is for short, single-line values; `text_area` is for longer, multi-line content.

```python theme={null}
import streamlit as st

name    = st.text_input("Your name", placeholder="e.g. Amit Patel")
email   = st.text_input("Email address", placeholder="amit@example.com")
bio     = st.text_area("Short bio", height=120, placeholder="Tell us about yourself…")

if name:
    st.write(f"Hello, {name}!")
```

## Selectbox, Radio, and Checkbox

These widgets handle single-choice and toggle selections:

```python theme={null}
import streamlit as st

# Drop-down — single choice from a list
city = st.selectbox("Choose city", ["Mumbai", "Delhi", "Bengaluru", "Hyderabad"])

# Radio buttons — visible options, single choice
gender = st.radio("Gender", ["Male", "Female", "Prefer not to say"])

# Checkbox — boolean toggle
agree = st.checkbox("I agree to the terms and conditions")

st.write(f"Selected city: {city}")
if agree:
    st.success("Thank you for agreeing!")
```

## Multiselect

Allow users to choose **multiple values** from a list:

```python theme={null}
import streamlit as st

skills    = st.multiselect("Select your skills", ["Python", "SQL", "Machine Learning", "FastAPI"])
languages = st.multiselect("Programming languages", ["Python", "JavaScript", "Java", "C++"])

if skills:
    st.write(f"You selected: {', '.join(skills)}")
```

## Number Input and Slider

For numeric values, choose between a text field with increment/decrement arrows or a draggable slider:

```python theme={null}
import streamlit as st

age    = st.number_input("Age", min_value=0, max_value=120, value=25, step=1)
salary = st.number_input("Monthly salary (₹)", min_value=0, value=50000, step=1000)
rating = st.slider("Customer rating", min_value=1, max_value=10, value=5)
budget = st.slider("Budget range (₹)", min_value=0, max_value=100000, value=(20000, 60000))

st.write(f"Age: {age}, Rating: {rating}")
st.write(f"Budget: ₹{budget[0]:,} – ₹{budget[1]:,}")
```

<Tip>
  Passing a tuple as the `value` argument to `st.slider` creates a **range slider** with two handles, perfect for price or date range filters.
</Tip>

## File Uploader

Let users upload files from their local machine. The returned object behaves like a file handle you can pass directly to Pandas or other libraries:

```python theme={null}
import streamlit as st
import pandas as pd

uploaded_file = st.file_uploader(
    "Upload a CSV file",
    type=["csv"],
    help="Only CSV files are accepted"
)

if uploaded_file is not None:
    df = pd.read_csv(uploaded_file)
    st.success(f"Loaded {len(df)} rows and {len(df.columns)} columns.")
    st.dataframe(df.head())
```

You can accept multiple file types simultaneously:

```python theme={null}
media = st.file_uploader("Upload image or document", type=["png", "jpg", "pdf"])
```

## Date and Time Inputs

Use date and time pickers for scheduling or filtering by date:

```python theme={null}
import streamlit as st
import datetime

birthday     = st.date_input("Date of birth", value=datetime.date(2000, 1, 1))
meeting_time = st.time_input("Meeting time", value=datetime.time(9, 0))

# Date range
start_date = st.date_input("Start date")
end_date   = st.date_input("End date")

st.write(f"Birthday: {birthday}")
st.write(f"Meeting at: {meeting_time}")
```

## Combining Widgets

In a real app, you'll combine multiple widgets and use their values together. Here's a simple employee filter:

```python theme={null}
import streamlit as st
import pandas as pd

employees = pd.DataFrame({
    "Name":       ["Rahul", "Anitha", "Kiran", "Sneha"],
    "City":       ["Hyderabad", "Bengaluru", "Hyderabad", "Chennai"],
    "Salary":     [65000, 55000, 72000, 50000],
    "Department": ["Engineering", "HR", "Engineering", "Sales"]
})

st.title("Employee Filter")

city    = st.selectbox("Filter by city", ["All"] + employees["City"].unique().tolist())
min_sal = st.slider("Minimum salary", 0, 100000, 50000, step=5000)

filtered = employees.copy()
if city != "All":
    filtered = filtered[filtered["City"] == city]
filtered = filtered[filtered["Salary"] >= min_sal]

st.dataframe(filtered)
st.info(f"Showing {len(filtered)} of {len(employees)} employees.")
```

<Note>
  All widget values are re-evaluated on every script rerun. If you need to persist a value across reruns (e.g., a counter or authenticated user), use `st.session_state` — covered in the Building Apps chapter.
</Note>
