Widgets are fundamental components in user interfaces, and in Streamlit, they allow you to create interactivity directly in your applications. With just a few lines of code, you can add buttons, checkboxes, selectors, and much more.
Main Input Widgets
st.checkbox()
Displays a checkbox that returns a Boolean value (True if checked, False otherwise).
Example:
import streamlit as st
agree = st.checkbox('I agree to the terms')
if agree:
st.write('Thank you for agreeing!')
st.button()
Displays a button that can be used to trigger actions.
Example:
if st.button('Click here!'):
st.write('Button pressed!')
st.radio()
Displays a set of radio buttons for single selection.
Example:
choice = st.radio('Choose a course:', ['Python', 'Data Science', 'Web Development'])
st.write(f'You chose: {choice}')
st.selectbox()
Allows selecting an item from a dropdown list.
Example:
city = st.selectbox('Choose a city:', ['Luanda', 'Maputo', 'Lisbon'])
st.write(f'Selected city: {city}')
st.multiselect()
Allows selecting multiple items from a list.
Example:
fruits = st.multiselect('Choose your favorite fruits:', ['Apple', 'Banana', 'Grapes', 'Mango'])
st.write(f'You chose: {", ".join(fruits)}')
st.slider()
Allows selecting a value from a range.
Example:
age = st.slider('What is your age?', 0, 100, 25)
st.write(f'Age: {age} years')
st.select_slider()
Similar to the slider but allows defining custom values.
Example:
mood = st.select_slider('How are you feeling today?', options=['Sad', 'Neutral', 'Happy'], value='Neutral')
st.write(f'Current mood: {mood}')
Additional Widgets
st.number_input()
For number input with control over minimum and maximum values.
Example:
number = st.number_input('Choose a number:', min_value=1, max_value=100, value=10)
st.write(f'Chosen number: {number}')
st.text_input()
For text input.
Example:
email = st.text_input('Enter your email:')
st.write(f'Email: {email}')
st.date_input()
For selecting a date.
Example:
date = st.date_input('Select a date:')
st.write(f'Selected date: {date}')
st.time_input()
For selecting a time.
Example:
time = st.time_input('Choose a time:')
st.write(f'Selected time: {time}')
st.text_area()
For multi-line text input.
Example:
description = st.text_area('Description:')
st.write(f'Provided description: {description}')
st.file_uploader()
For file uploads.
Example:
file = st.file_uploader('Upload a file:', type=['png', 'jpg', 'pdf'])
if file:
st.write(f'Uploaded file: {file.name}')
st.color_picker()
For selecting a color.
Example:
color = st.color_picker('Choose a color:')
st.write(f'Selected color: {color}')
With these widgets, you can create highly interactive applications and provide a seamless user experience.
Copyright statement: Unless otherwise indicated, all articles are original to this site, please cite the source when sharing.
Article link:http://pybeginners.com/python-streamlit/input-widgets-in-streamlit/
License agreement:Creative Commons Attribution-NonCommercial 4.0 International License