掌握 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中文網其他相關文章!

Linux終端中查看Python版本時遇到權限問題的解決方法當你在Linux終端中嘗試查看Python的版本時,輸入python...

本文解釋瞭如何使用美麗的湯庫來解析html。 它詳細介紹了常見方法,例如find(),find_all(),select()和get_text(),以用於數據提取,處理不同的HTML結構和錯誤以及替代方案(SEL)

Python的statistics模塊提供強大的數據統計分析功能,幫助我們快速理解數據整體特徵,例如生物統計學和商業分析等領域。無需逐個查看數據點,只需查看均值或方差等統計量,即可發現原始數據中可能被忽略的趨勢和特徵,並更輕鬆、有效地比較大型數據集。 本教程將介紹如何計算平均值和衡量數據集的離散程度。除非另有說明,本模塊中的所有函數都支持使用mean()函數計算平均值,而非簡單的求和平均。 也可使用浮點數。 import random import statistics from fracti

本文比較了Tensorflow和Pytorch的深度學習。 它詳細介紹了所涉及的步驟:數據準備,模型構建,培訓,評估和部署。 框架之間的關鍵差異,特別是關於計算刻度的

本文討論了諸如Numpy,Pandas,Matplotlib,Scikit-Learn,Tensorflow,Tensorflow,Django,Blask和請求等流行的Python庫,並詳細介紹了它們在科學計算,數據分析,可視化,機器學習,網絡開發和H中的用途

本文指導Python開發人員構建命令行界面(CLIS)。 它使用Typer,Click和ArgParse等庫詳細介紹,強調輸入/輸出處理,並促進用戶友好的設計模式,以提高CLI可用性。

在使用Python的pandas庫時,如何在兩個結構不同的DataFrame之間進行整列複製是一個常見的問題。假設我們有兩個Dat...

文章討論了虛擬環境在Python中的作用,重點是管理項目依賴性並避免衝突。它詳細介紹了他們在改善項目管理和減少依賴問題方面的創建,激活和利益。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

SublimeText3漢化版
中文版,非常好用

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

Atom編輯器mac版下載
最受歡迎的的開源編輯器

記事本++7.3.1
好用且免費的程式碼編輯器

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),