搜索
首页后端开发Python教程Streamlit 部分掌握输入小部件

Streamlit Part Mastering Input Widgets

掌握 Streamlit 中的输入小部件:综合指南

?获取代码:GitHub - jamesbmour/blog_tutorials

?相关Streamlit教程:JustCodeIt

Streamlit 彻底改变了我们使用 Python 创建 Web 应用程序的方式。它的简单性和强大功能使其成为数据科学家和开发人员的绝佳选择。在这篇文章中,我们将深入探讨 Streamlit 最强大的功能之一:输入小部件。我们将探索 16 种不同的输入类型,演示如何在 Streamlit 应用程序中有效地使用它们。

设置我们的 Streamlit 应用程序

在我们深入了解小部件之前,让我们先设置一下 Streamlit 应用程序:

import streamlit as st

st.set_page_config(layout="wide")
st.title("Streamlit Part 4: Inputs in Streamlit")

col1, col2 = st.columns(2)

我们导入了 Streamlit,将页面设置为宽布局,添加了标题,并创建了两列以更好地组织我们的小部件。

按钮输入

1. 基本按钮

最简单的输入形式是按钮。创建方法如下:

with col1:
    st.subheader("1. Button")
    btn1 = st.button("Click Me", key="button", help="Click me to see the magic", type='secondary', disabled=False)
    if btn1:
        st.write("Button Clicked")

详细说明:

  • st.button() 函数创建一个可点击的按钮。
  • key:按钮的唯一标识符,当您有多个按钮时很有用。
  • help:将鼠标悬停在按钮上时出现的工具提示文本。
  • type:确定按钮的外观(“主要”、“次要”等)。
  • 禁用:如果设置为True,按钮将变灰且不可点击。

用例:

  • 触发数据处理或模型训练
  • 提交表格
  • 刷新数据或图表

提示:使用按钮状态来控制应用程序的流程,例如显示/隐藏部分或触发计算。

2. 链接按钮

要将用户重定向到外部链接,请使用链接按钮:

st.subheader("2. Link Button")
if st.link_button("Click Me", "<https:></https:>"):
    st.write("Link Button Clicked")

详细说明:

  • st.link_button() 创建一个按钮,单击该按钮会打开一个具有指定 URL 的新选项卡。
  • 第一个参数是按钮文本,第二个参数是 URL。

用例:

  • 链接到文档或外部资源
  • 重定向至社交媒体个人资料
  • 连接到相关网络应用程序

提示:谨慎使用链接按钮,以避免不必要地引导用户离开您的应用。

3. 下载按钮

允许用户直接从您的应用下载文件:

st.subheader("3. Download Button")
if st.download_button("Download Me", "hello world", "hello.txt", mime='text/plain'):
    st.write("Download Button Clicked")

详细说明:

  • st.download_button() 创建一个按钮,单击时会触发文件下载。
  • 参数:按钮标签、文件内容、文件名和 MIME 类型。
  • MIME 类型指定文件类型(例如,.txt 为“text/plain”,.pdf 为“application/pdf”)。

用例:

  • 下载生成的报告或数据
  • 保存处理后的图像或图表
  • 导出用户创建的内容

提示:您可以根据用户交互或数据处理结果动态生成文件内容。

选择小部件

4. 复选框

复选框非常适合切换选项:

st.subheader("4. Checkbox")
checkbox_val = st.checkbox("Check Me", value=False)
if checkbox_val:
    st.write("Checkbox Checked")

详细说明:

  • st.checkbox() 创建一个可切换的复选框。
  • value 参数设置初始状态(True/False)。

用例:

  • 启用/禁用应用程序中的功能
  • 从列表中选择多个选项
  • 创建简单的是/否问题

提示:使用复选框来控制应用程序中其他元素的可见性,以获得更动态的用户体验。

5. 单选按钮

当用户需要从列表中选择一个选项时:

st.subheader("5. Radio")
radio_val = st.radio("Select Color", ["Red", "Green", "Blue"], index=0)
if radio_val:
    st.write(f"You selected {radio_val}")

详细说明:

  • st.radio() 创建一组单选按钮。
  • 第一个参数是标签,后跟选项列表。
  • index 指定默认选择的选项(从 0 开始)。

用例:

  • 在互斥选项之间进行选择
  • 设置应用模式或主题
  • 根据类别过滤数据

提示:当您有少量互斥选项(通常是 2-5 个)时,请使用单选按钮。

6. 选择框

对于下拉选择:

st.subheader("6. Selectbox")
select_val = st.selectbox("Select Color", ["Red", "Green", "Blue", "Black"], index=1)
if select_val:
    st.write(f"You selected {select_val}")

详细说明:

  • st.selectbox() 创建一个下拉菜单。
  • 与单选按钮类似,但更适合较长的选项列表。
  • index 设置默认选择的选项。

用例:

  • Selecting from a long list of options
  • Choosing categories or filters
  • Setting parameters for data analysis

Tip: You can populate the options dynamically based on data or user inputs.

7. Multi-select

Allow users to select multiple options:

st.subheader("7. Multiselect")
multiselect_val = st.multiselect("Select Colors", ["Red", "Green", "Blue", "Black"], default=["Red"])
if multiselect_val:
    st.write(f"You selected {multiselect_val}")

Detailed Explanation:

  • st.multiselect() creates a dropdown that allows multiple selections.
  • default sets the initially selected options.

Use Cases:

  • Selecting multiple filters for data
  • Choosing features for a machine learning model
  • Creating customizable dashboards

Tip: Use st.multiselect() when you want users to be able to select any number of options, including none or all.

8. Select Slider

For selecting from a range of discrete values:

st.subheader("8. Select Slider")
select_slider_val = st.select_slider("Select Value", options=range(1, 101), value=50)
if select_slider_val:
    st.write(f"You selected {select_slider_val}")

Detailed Explanation:

  • st.select_slider() creates a slider with discrete values.
  • options can be a range of numbers or a list of any values (even strings).
  • value sets the initial position of the slider.

Use Cases:

  • Selecting from a range of predefined values
  • Creating rating systems
  • Adjusting parameters with specific increments

Tip: You can use custom labels for the slider by passing a list of tuples (label, value) as options.

Text Inputs

9. Text Input

For single-line text input:

with col2:
    st.subheader("9. Text Input")
    text_input_val = st.text_input("Enter some text", value="", max_chars=50)
    if text_input_val:
        st.write(f"You entered {text_input_val}")

Detailed Explanation:

  • st.text_input() creates a single-line text input field.
  • value sets the initial text (if any).
  • max_chars limits the number of characters that can be entered.

Use Cases:

  • Getting user names or short responses
  • Inputting search queries
  • Entering simple parameters or values

Tip: Use the type parameter to create password fields or other specialized inputs.

10. Text Area

For multi-line text input:

st.subheader("10. Text Area")
text_area_val = st.text_area("Enter some text", value="", height=150, max_chars=200)
if text_area_val:
    st.write(f"You entered {text_area_val}")

Detailed Explanation:

  • st.text_area() creates a multi-line text input box.
  • height sets the vertical size of the box.
  • max_chars limits the total character count.

Use Cases:

  • Collecting longer text responses or comments
  • Inputting multi-line code snippets
  • Creating text-based data entry forms

Tip: You can use st.text_area() with natural language processing models for text analysis or generation tasks.

Numeric and Date/Time Inputs

11. Number Input

For numerical inputs:

st.subheader("11. Number Input")
number_input_val = st.number_input("Enter a number", value=0, min_value=0, max_value=100, step=1)
if number_input_val:
    st.write(f"You entered {number_input_val}")

Detailed Explanation:

  • st.number_input() creates a field for numerical input.
  • min_value and max_value set the allowed range.
  • step defines the increment/decrement step.

Use Cases:

  • Inputting quantities or amounts
  • Setting numerical parameters for algorithms
  • Creating age or rating inputs

Tip: You can use format parameter to control the display of decimal places.

12. Date Input

For selecting dates:

st.subheader("12. Date Input")
date_input_val = st.date_input("Enter a date")
if date_input_val:
    st.write(f"You selected {date_input_val}")

Detailed Explanation:

  • st.date_input() creates a date picker widget.
  • You can set min_value and max_value to limit the date range.

Use Cases:

  • Selecting dates for data filtering
  • Setting deadlines or event dates
  • Inputting birthdates or other significant dates

Tip: Use datetime.date.today() as the default value to start with the current date.

13. Time Input

For selecting times:

st.subheader("13. Time Input")
time_input_val = st.time_input("Enter a time")
if time_input_val:
    st.write(f"You selected {time_input_val}")

Detailed Explanation:

  • st.time_input() creates a time picker widget.
  • Returns a datetime.time object.

Use Cases:

  • Setting appointment times
  • Configuring schedules
  • Inputting time-based parameters

Tip: Combine with st.date_input() to create full datetime inputs.

Advanced Inputs

14. File Uploader

For uploading files:

st.subheader("14. File Uploader")
file_uploader_val = st.file_uploader("Upload a file", type=["png", "jpg", "txt"])
if file_uploader_val:
    st.write(f"You uploaded {file_uploader_val.name}")

Detailed Explanation:

  • st.file_uploader() creates a file upload widget.
  • type parameter limits the allowed file types.
  • Returns a UploadedFile object that you can process.

Use Cases:

  • Uploading images for processing
  • Importing data files for analysis
  • Allowing users to upload documents or media

Tip: Use st.file_uploader() in combination with libraries like Pillow or pandas to process uploaded files directly in your app.

15. Color Picker

For selecting colors:

st.subheader("15. Color Picker")
color_picker_val = st.color_picker("Pick a color", value="#00f900")
if color_picker_val:
    st.write(f"You picked {color_picker_val}")

Detailed Explanation:

  • st.color_picker() creates a color selection widget.
  • Returns the selected color as a hex string.

Use Cases:

  • Customizing UI elements
  • Selecting colors for data visualization
  • Creating design tools

Tip: You can use the selected color to dynamically update the appearance of other elements in your app.

16. Camera Input

For capturing images using the device's camera:

st.subheader("16. Camera Input")
camera_input_val = st.camera_input("Take a picture", help="Capture an image using your camera")
if camera_input_val:
    st.write("Picture captured successfully")

Detailed Explanation:

  • st.camera_input() creates a widget that accesses the user's camera.
  • Returns an image file that can be processed or displayed.

Use Cases:

  • Real-time image processing applications
  • Document scanning features
  • Interactive computer vision demos

Tip: Combine with image processing libraries like OpenCV to perform real-time analysis on captured images.

Conclusion

Streamlit's input widgets provide a powerful and flexible way to create interactive web applications. From simple buttons to complex file uploaders and camera inputs, these widgets cover a wide range of use cases. By mastering these input types, you can create rich, interactive Streamlit apps that engage users and provide meaningful interactions with your data and models.

Happy Streamlit coding!

? Get the Code: GitHub - jamesbmour/blog_tutorials
? Related Streamlit Tutorials:JustCodeIt
? Support my work: Buy Me a Coffee

以上是Streamlit 部分掌握输入小部件的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
如何使用Python查找文本文件的ZIPF分布如何使用Python查找文本文件的ZIPF分布Mar 05, 2025 am 09:58 AM

本教程演示如何使用Python处理Zipf定律这一统计概念,并展示Python在处理该定律时读取和排序大型文本文件的效率。 您可能想知道Zipf分布这个术语是什么意思。要理解这个术语,我们首先需要定义Zipf定律。别担心,我会尽量简化说明。 Zipf定律 Zipf定律简单来说就是:在一个大型自然语言语料库中,最频繁出现的词的出现频率大约是第二频繁词的两倍,是第三频繁词的三倍,是第四频繁词的四倍,以此类推。 让我们来看一个例子。如果您查看美国英语的Brown语料库,您会注意到最频繁出现的词是“th

我如何使用美丽的汤来解析HTML?我如何使用美丽的汤来解析HTML?Mar 10, 2025 pm 06:54 PM

本文解释了如何使用美丽的汤库来解析html。 它详细介绍了常见方法,例如find(),find_all(),select()和get_text(),以用于数据提取,处理不同的HTML结构和错误以及替代方案(SEL)

python中的图像过滤python中的图像过滤Mar 03, 2025 am 09:44 AM

处理嘈杂的图像是一个常见的问题,尤其是手机或低分辨率摄像头照片。 本教程使用OpenCV探索Python中的图像过滤技术来解决此问题。 图像过滤:功能强大的工具 图像过滤器

如何使用TensorFlow或Pytorch进行深度学习?如何使用TensorFlow或Pytorch进行深度学习?Mar 10, 2025 pm 06:52 PM

本文比较了Tensorflow和Pytorch的深度学习。 它详细介绍了所涉及的步骤:数据准备,模型构建,培训,评估和部署。 框架之间的关键差异,特别是关于计算刻度的

Python中的平行和并发编程简介Python中的平行和并发编程简介Mar 03, 2025 am 10:32 AM

Python是数据科学和处理的最爱,为高性能计算提供了丰富的生态系统。但是,Python中的并行编程提出了独特的挑战。本教程探讨了这些挑战,重点是全球解释

如何在Python中实现自己的数据结构如何在Python中实现自己的数据结构Mar 03, 2025 am 09:28 AM

本教程演示了在Python 3中创建自定义管道数据结构,利用类和操作员超载以增强功能。 管道的灵活性在于它能够将一系列函数应用于数据集的能力,GE

python对象的序列化和避难所化:第1部分python对象的序列化和避难所化:第1部分Mar 08, 2025 am 09:39 AM

Python 对象的序列化和反序列化是任何非平凡程序的关键方面。如果您将某些内容保存到 Python 文件中,如果您读取配置文件,或者如果您响应 HTTP 请求,您都会进行对象序列化和反序列化。 从某种意义上说,序列化和反序列化是世界上最无聊的事情。谁会在乎所有这些格式和协议?您想持久化或流式传输一些 Python 对象,并在以后完整地取回它们。 这是一种在概念层面上看待世界的好方法。但是,在实际层面上,您选择的序列化方案、格式或协议可能会决定程序运行的速度、安全性、维护状态的自由度以及与其他系

Python中的数学模块:统计Python中的数学模块:统计Mar 09, 2025 am 11:40 AM

Python的statistics模块提供强大的数据统计分析功能,帮助我们快速理解数据整体特征,例如生物统计学和商业分析等领域。无需逐个查看数据点,只需查看均值或方差等统计量,即可发现原始数据中可能被忽略的趋势和特征,并更轻松、有效地比较大型数据集。 本教程将介绍如何计算平均值和衡量数据集的离散程度。除非另有说明,本模块中的所有函数都支持使用mean()函数计算平均值,而非简单的求和平均。 也可使用浮点数。 import random import statistics from fracti

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
2 周前By尊渡假赌尊渡假赌尊渡假赌
仓库:如何复兴队友
1 个月前By尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒险:如何获得巨型种子
4 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具

安全考试浏览器

安全考试浏览器

Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)