Interactive widgets for user input and interaction. These widgets enable user engagement and data collection in Streamlit applications.
Interactive button elements for triggering actions and navigation.
def button(label, key=None, help=None, on_click=None, args=None, kwargs=None, type="secondary", disabled=False, use_container_width=False, icon=None):
"""
Display a button widget.
Parameters:
- label (str): Button label text
- key (str): Unique key for the widget
- help (str): Optional tooltip text
- on_click (callable): Function to call when clicked
- args (tuple): Arguments to pass to on_click function
- kwargs (dict): Keyword arguments to pass to on_click function
- type (str): Button type ('primary' or 'secondary')
- disabled (bool): Disable the button
- use_container_width (bool): Use full container width
- icon (str): Optional icon name
Returns:
bool: True if button was clicked, False otherwise
"""
def download_button(label, data, file_name=None, mime=None, key=None, help=None, on_click=None, args=None, kwargs=None, disabled=False, use_container_width=False, icon=None):
"""
Display a download button widget.
Parameters:
- label (str): Button label text
- data: Data to download (str, bytes, file-like object, or DataFrame)
- file_name (str): Suggested filename for download
- mime (str): MIME type of the data
- key (str): Unique key for the widget
- help (str): Optional tooltip text
- on_click (callable): Function to call when clicked
- args (tuple): Arguments to pass to on_click function
- kwargs (dict): Keyword arguments to pass to on_click function
- disabled (bool): Disable the button
- use_container_width (bool): Use full container width
- icon (str): Optional icon name
Returns:
bool: True if button was clicked, False otherwise
"""
def link_button(label, url, help=None, disabled=False, use_container_width=False, icon=None):
"""
Display a button that opens a URL when clicked.
Parameters:
- label (str): Button label text
- url (str): URL to open
- help (str): Optional tooltip text
- disabled (bool): Disable the button
- use_container_width (bool): Use full container width
- icon (str): Optional icon name
Returns:
bool: True if button was clicked, False otherwise
"""
def page_link(page, label=None, icon=None, help=None, disabled=False, use_container_width=False):
"""
Display a link to another page in a multipage app.
Parameters:
- page: Page object or path to link to
- label (str): Link label text (defaults to page title)
- icon (str): Optional icon name
- help (str): Optional tooltip text
- disabled (bool): Disable the link
- use_container_width (bool): Use full container width
Returns:
bool: True if link was clicked, False otherwise
"""Text input widgets for collecting user text input.
def text_input(label, value="", max_chars=None, key=None, type="default", help=None, autocomplete=None, on_change=None, args=None, kwargs=None, placeholder=None, disabled=False, label_visibility="visible"):
"""
Display a single-line text input widget.
Parameters:
- label (str): Widget label
- value (str): Initial value
- max_chars (int): Maximum number of characters
- key (str): Unique key for the widget
- type (str): Input type ('default' or 'password')
- help (str): Optional tooltip text
- autocomplete (str): HTML autocomplete attribute
- on_change (callable): Function to call when value changes
- args (tuple): Arguments to pass to on_change function
- kwargs (dict): Keyword arguments to pass to on_change function
- placeholder (str): Placeholder text
- disabled (bool): Disable the widget
- label_visibility (str): Label visibility ('visible', 'hidden', 'collapsed')
Returns:
str: Current text input value
"""
def text_area(label, value="", height=None, max_chars=None, key=None, help=None, on_change=None, args=None, kwargs=None, placeholder=None, disabled=False, label_visibility="visible"):
"""
Display a multi-line text input widget.
Parameters:
- label (str): Widget label
- value (str): Initial value
- height (int): Height in pixels
- max_chars (int): Maximum number of characters
- key (str): Unique key for the widget
- help (str): Optional tooltip text
- on_change (callable): Function to call when value changes
- args (tuple): Arguments to pass to on_change function
- kwargs (dict): Keyword arguments to pass to on_change function
- placeholder (str): Placeholder text
- disabled (bool): Disable the widget
- label_visibility (str): Label visibility ('visible', 'hidden', 'collapsed')
Returns:
str: Current text area value
"""Widgets for numeric input and selection.
def number_input(label, min_value=None, max_value=None, value=None, step=None, format=None, key=None, help=None, on_change=None, args=None, kwargs=None, disabled=False, label_visibility="visible", placeholder=None):
"""
Display a numeric input widget.
Parameters:
- label (str): Widget label
- min_value (float): Minimum allowed value
- max_value (float): Maximum allowed value
- value (float): Initial value
- step (float): Step size for increment/decrement
- format (str): Number format string
- key (str): Unique key for the widget
- help (str): Optional tooltip text
- on_change (callable): Function to call when value changes
- args (tuple): Arguments to pass to on_change function
- kwargs (dict): Keyword arguments to pass to on_change function
- disabled (bool): Disable the widget
- label_visibility (str): Label visibility ('visible', 'hidden', 'collapsed')
- placeholder (str): Placeholder text
Returns:
float or int: Current numeric value
"""
def slider(label, min_value=None, max_value=None, value=None, step=None, format=None, key=None, help=None, on_change=None, args=None, kwargs=None, disabled=False, label_visibility="visible"):
"""
Display a slider widget.
Parameters:
- label (str): Widget label
- min_value (float): Minimum value
- max_value (float): Maximum value
- value (float or tuple): Initial value(s) - single value or (min, max) for range
- step (float): Step size
- format (str): Value format string
- key (str): Unique key for the widget
- help (str): Optional tooltip text
- on_change (callable): Function to call when value changes
- args (tuple): Arguments to pass to on_change function
- kwargs (dict): Keyword arguments to pass to on_change function
- disabled (bool): Disable the widget
- label_visibility (str): Label visibility ('visible', 'hidden', 'collapsed')
Returns:
float or tuple: Current slider value(s)
"""
def select_slider(label, options=(), value=None, format_func=None, key=None, help=None, on_change=None, args=None, kwargs=None, disabled=False, label_visibility="visible"):
"""
Display a slider widget for selecting from discrete options.
Parameters:
- label (str): Widget label
- options (sequence): List of options to select from
- value: Initial selected value
- format_func (callable): Function to format option display
- key (str): Unique key for the widget
- help (str): Optional tooltip text
- on_change (callable): Function to call when value changes
- args (tuple): Arguments to pass to on_change function
- kwargs (dict): Keyword arguments to pass to on_change function
- disabled (bool): Disable the widget
- label_visibility (str): Label visibility ('visible', 'hidden', 'collapsed')
Returns:
Any: Currently selected value
"""Widgets for selecting from predefined options.
def selectbox(label, options, index=0, format_func=None, key=None, help=None, on_change=None, args=None, kwargs=None, disabled=False, label_visibility="visible", placeholder="Choose an option"):
"""
Display a select widget (dropdown).
Parameters:
- label (str): Widget label
- options (sequence): List of options to select from
- index (int): Index of initially selected option
- format_func (callable): Function to format option display
- key (str): Unique key for the widget
- help (str): Optional tooltip text
- on_change (callable): Function to call when value changes
- args (tuple): Arguments to pass to on_change function
- kwargs (dict): Keyword arguments to pass to on_change function
- disabled (bool): Disable the widget
- label_visibility (str): Label visibility ('visible', 'hidden', 'collapsed')
- placeholder (str): Placeholder text when no option selected
Returns:
Any: Currently selected option
"""
def multiselect(label, options, default=None, format_func=None, key=None, help=None, on_change=None, args=None, kwargs=None, disabled=False, label_visibility="visible", max_selections=None, placeholder="Choose an option"):
"""
Display a multiselect widget.
Parameters:
- label (str): Widget label
- options (sequence): List of options to select from
- default (list): Initially selected options
- format_func (callable): Function to format option display
- key (str): Unique key for the widget
- help (str): Optional tooltip text
- on_change (callable): Function to call when value changes
- args (tuple): Arguments to pass to on_change function
- kwargs (dict): Keyword arguments to pass to on_change function
- disabled (bool): Disable the widget
- label_visibility (str): Label visibility ('visible', 'hidden', 'collapsed')
- max_selections (int): Maximum number of selections allowed
- placeholder (str): Placeholder text when no options selected
Returns:
list: Currently selected options
"""
def radio(label, options, index=0, format_func=None, key=None, help=None, on_change=None, args=None, kwargs=None, disabled=False, horizontal=False, captions=None, selection_mode="single", label_visibility="visible"):
"""
Display a radio button widget.
Parameters:
- label (str): Widget label
- options (sequence): List of options to select from
- index (int): Index of initially selected option
- format_func (callable): Function to format option display
- key (str): Unique key for the widget
- help (str): Optional tooltip text
- on_change (callable): Function to call when value changes
- args (tuple): Arguments to pass to on_change function
- kwargs (dict): Keyword arguments to pass to on_change function
- disabled (bool): Disable the widget
- horizontal (bool): Display options horizontally
- captions (list): Optional captions for each option
- selection_mode (str): Selection mode ('single')
- label_visibility (str): Label visibility ('visible', 'hidden', 'collapsed')
Returns:
Any: Currently selected option
"""
def checkbox(label, value=False, key=None, help=None, on_change=None, args=None, kwargs=None, disabled=False, label_visibility="visible"):
"""
Display a checkbox widget.
Parameters:
- label (str): Widget label
- value (bool): Initial checkbox state
- key (str): Unique key for the widget
- help (str): Optional tooltip text
- on_change (callable): Function to call when value changes
- args (tuple): Arguments to pass to on_change function
- kwargs (dict): Keyword arguments to pass to on_change function
- disabled (bool): Disable the widget
- label_visibility (str): Label visibility ('visible', 'hidden', 'collapsed')
Returns:
bool: Current checkbox state
"""
def toggle(label, value=False, key=None, help=None, on_change=None, args=None, kwargs=None, disabled=False, label_visibility="visible"):
"""
Display a toggle switch widget.
Parameters:
- label (str): Widget label
- value (bool): Initial toggle state
- key (str): Unique key for the widget
- help (str): Optional tooltip text
- on_change (callable): Function to call when value changes
- args (tuple): Arguments to pass to on_change function
- kwargs (dict): Keyword arguments to pass to on_change function
- disabled (bool): Disable the widget
- label_visibility (str): Label visibility ('visible', 'hidden', 'collapsed')
Returns:
bool: Current toggle state
"""Contemporary selection interfaces with enhanced user experience.
def pills(label, options, selection_mode="single", format_func=None, default=None, key=None, help=None, on_change=None, args=None, kwargs=None, disabled=False, label_visibility="visible"):
"""
Display a pills widget for selection.
Parameters:
- label (str): Widget label
- options (sequence): List of options to select from
- selection_mode (str): Selection mode ('single' or 'multi')
- format_func (callable): Function to format option display
- default: Initially selected option(s)
- key (str): Unique key for the widget
- help (str): Optional tooltip text
- on_change (callable): Function to call when value changes
- args (tuple): Arguments to pass to on_change function
- kwargs (dict): Keyword arguments to pass to on_change function
- disabled (bool): Disable the widget
- label_visibility (str): Label visibility ('visible', 'hidden', 'collapsed')
Returns:
Any or list: Currently selected option(s)
"""
def segmented_control(label, options, selection_mode="single", format_func=None, default=None, key=None, help=None, on_change=None, args=None, kwargs=None, disabled=False, label_visibility="visible"):
"""
Display a segmented control widget.
Parameters:
- label (str): Widget label
- options (sequence): List of options to select from
- selection_mode (str): Selection mode ('single' or 'multi')
- format_func (callable): Function to format option display
- default: Initially selected option(s)
- key (str): Unique key for the widget
- help (str): Optional tooltip text
- on_change (callable): Function to call when value changes
- args (tuple): Arguments to pass to on_change function
- kwargs (dict): Keyword arguments to pass to on_change function
- disabled (bool): Disable the widget
- label_visibility (str): Label visibility ('visible', 'hidden', 'collapsed')
Returns:
Any or list: Currently selected option(s)
"""Widgets for temporal input and selection.
def date_input(label, value="today", min_value=None, max_value=None, key=None, help=None, on_change=None, args=None, kwargs=None, format="YYYY/MM/DD", disabled=False, label_visibility="visible"):
"""
Display a date input widget.
Parameters:
- label (str): Widget label
- value: Initial date value ('today', date object, or None)
- min_value (date): Minimum selectable date
- max_value (date): Maximum selectable date
- key (str): Unique key for the widget
- help (str): Optional tooltip text
- on_change (callable): Function to call when value changes
- args (tuple): Arguments to pass to on_change function
- kwargs (dict): Keyword arguments to pass to on_change function
- format (str): Date display format
- disabled (bool): Disable the widget
- label_visibility (str): Label visibility ('visible', 'hidden', 'collapsed')
Returns:
date or None: Selected date
"""
def time_input(label, value=None, key=None, help=None, on_change=None, args=None, kwargs=None, disabled=False, label_visibility="visible", step=60):
"""
Display a time input widget.
Parameters:
- label (str): Widget label
- value (time): Initial time value
- key (str): Unique key for the widget
- help (str): Optional tooltip text
- on_change (callable): Function to call when value changes
- args (tuple): Arguments to pass to on_change function
- kwargs (dict): Keyword arguments to pass to on_change function
- disabled (bool): Disable the widget
- label_visibility (str): Label visibility ('visible', 'hidden', 'collapsed')
- step (int): Step size in seconds
Returns:
time: Selected time
"""Widgets for file uploads and media capture.
def file_uploader(label, type=None, accept_multiple_files=False, key=None, help=None, on_change=None, args=None, kwargs=None, disabled=False, label_visibility="visible"):
"""
Display a file uploader widget.
Parameters:
- label (str): Widget label
- type (str or list): Allowed file extensions (e.g., 'csv', ['png', 'jpg'])
- accept_multiple_files (bool): Allow multiple file selection
- key (str): Unique key for the widget
- help (str): Optional tooltip text
- on_change (callable): Function to call when files change
- args (tuple): Arguments to pass to on_change function
- kwargs (dict): Keyword arguments to pass to on_change function
- disabled (bool): Disable the widget
- label_visibility (str): Label visibility ('visible', 'hidden', 'collapsed')
Returns:
UploadedFile or list or None: Uploaded file(s)
"""
def camera_input(label, key=None, help=None, on_change=None, args=None, kwargs=None, disabled=False, label_visibility="visible"):
"""
Display a camera input widget for taking photos.
Parameters:
- label (str): Widget label
- key (str): Unique key for the widget
- help (str): Optional tooltip text
- on_change (callable): Function to call when photo is taken
- args (tuple): Arguments to pass to on_change function
- kwargs (dict): Keyword arguments to pass to on_change function
- disabled (bool): Disable the widget
- label_visibility (str): Label visibility ('visible', 'hidden', 'collapsed')
Returns:
UploadedFile or None: Captured photo
"""
def audio_input(label, key=None, help=None, on_change=None, args=None, kwargs=None, disabled=False, label_visibility="visible"):
"""
Display an audio input widget for recording audio.
Parameters:
- label (str): Widget label
- key (str): Unique key for the widget
- help (str): Optional tooltip text
- on_change (callable): Function to call when audio is recorded
- args (tuple): Arguments to pass to on_change function
- kwargs (dict): Keyword arguments to pass to on_change function
- disabled (bool): Disable the widget
- label_visibility (str): Label visibility ('visible', 'hidden', 'collapsed')
Returns:
UploadedFile or None: Recorded audio
"""
def color_picker(label, value=None, key=None, help=None, on_change=None, args=None, kwargs=None, disabled=False, label_visibility="visible"):
"""
Display a color picker widget.
Parameters:
- label (str): Widget label
- value (str): Initial color value (hex format)
- key (str): Unique key for the widget
- help (str): Optional tooltip text
- on_change (callable): Function to call when color changes
- args (tuple): Arguments to pass to on_change function
- kwargs (dict): Keyword arguments to pass to on_change function
- disabled (bool): Disable the widget
- label_visibility (str): Label visibility ('visible', 'hidden', 'collapsed')
Returns:
str: Selected color in hex format
"""Form-specific input widgets and controls.
def form_submit_button(label="Submit", help=None, on_click=None, args=None, kwargs=None, type="secondary", disabled=False, use_container_width=False, icon=None):
"""
Display a form submit button.
Parameters:
- label (str): Button label
- help (str): Optional tooltip text
- on_click (callable): Function to call when clicked
- args (tuple): Arguments to pass to on_click function
- kwargs (dict): Keyword arguments to pass to on_click function
- type (str): Button type ('primary' or 'secondary')
- disabled (bool): Disable the button
- use_container_width (bool): Use full container width
- icon (str): Optional icon name
Returns:
bool: True if form was submitted, False otherwise
"""import streamlit as st
# Text inputs
name = st.text_input("Enter your name:")
description = st.text_area("Tell us about yourself:", height=100)
# Numeric inputs
age = st.number_input("Age:", min_value=0, max_value=120, value=25)
rating = st.slider("Rate your experience:", 1, 10, 5)
# Selection widgets
city = st.selectbox("Select your city:", ["New York", "London", "Tokyo"])
hobbies = st.multiselect("Select hobbies:", ["Reading", "Sports", "Music", "Travel"])
newsletter = st.checkbox("Subscribe to newsletter")# Button with callback
def on_button_click():
st.session_state.clicked = True
if st.button("Click me!", on_click=on_button_click):
st.success("Button was clicked!")
# File upload with type restrictions
uploaded_file = st.file_uploader(
"Choose a CSV file",
type=['csv'],
help="Upload a CSV file for analysis"
)
if uploaded_file is not None:
df = pd.read_csv(uploaded_file)
st.dataframe(df)
# Date range selection
from datetime import date, timedelta
start_date = st.date_input(
"Start date",
value=date.today() - timedelta(days=7)
)
end_date = st.date_input("End date", value=date.today())
if start_date > end_date:
st.error("Start date must be before end date")Interactive chat interface components for building conversational applications.
def chat_input(placeholder="Your message", key=None, max_chars=None, accept_file=False, file_type=None, disabled=False, on_submit=None, args=None, kwargs=None, width="stretch"):
"""
Display a chat input widget for conversational interfaces.
Parameters:
- placeholder (str): Placeholder text when input is empty
- key (str): Unique key for the widget
- max_chars (int): Maximum number of characters allowed
- accept_file (bool, "multiple", "directory"): File acceptance configuration
- file_type (str or list): Accepted file types (e.g., [".jpg", ".png"])
- disabled (bool): Disable the input widget
- on_submit (callable): Function to call on submission
- args (tuple): Arguments to pass to on_submit function
- kwargs (dict): Keyword arguments to pass to on_submit function
- width (str): Widget width configuration
Returns:
str or ChatInputValue or None: User input text or file data, None if no input
"""
def chat_message(name, avatar=None, width="stretch"):
"""
Insert a chat message container for conversational interfaces.
Parameters:
- name (str): Message author name ("user", "assistant", "ai", "human", or custom)
- avatar (str or image): Avatar image or emoji for the message
- width (str): Container width configuration
Returns:
DeltaGenerator: Container for chat message content
"""import streamlit as st
# Initialize chat history
if "messages" not in st.session_state:
st.session_state.messages = []
# Display chat messages from history
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
# Chat input
if prompt := st.chat_input("What would you like to know?"):
# Add user message to chat history
st.session_state.messages.append({"role": "user", "content": prompt})
with st.chat_message("user"):
st.markdown(prompt)
# Generate assistant response
response = f"Echo: {prompt}"
st.session_state.messages.append({"role": "assistant", "content": response})
with st.chat_message("assistant"):
st.markdown(response)
# Chat input with file upload
prompt = st.chat_input("Send a message", accept_file="multiple", file_type=[".txt", ".py", ".md"])
if prompt:
if hasattr(prompt, 'message') and hasattr(prompt, 'files'):
st.write(f"Message: {prompt.message}")
st.write(f"Files: {[f.name for f in prompt.files]}")
else:
st.write(f"Text message: {prompt}")