常用 Widgets
先把 Widget 當普通變數用。使用者操作後,下次重跑時這個變數就是新值。
日常最常用的幾個
| 指令 | 用途 |
|---|---|
st.slider |
數字或範圍 |
st.number_input |
精確數字 |
st.selectbox |
單選下拉 |
st.multiselect |
多選 |
st.radio |
單選圓鈕 |
st.checkbox |
開關,常用來顯示/隱藏區塊 |
st.text_input |
單行文字 |
st.text_area |
多行文字 |
st.date_input |
日期 |
st.file_uploader |
上傳 CSV、圖片等 |
st.button |
一次性動作 |
st.download_button |
下載檔案 |
name = st.text_input("名字")
city = st.selectbox("城市", ["台北", "台中", "高雄"])
show = st.checkbox("顯示摘要")
if show:
st.write(f"{name} 住在 {city}")
key 與 Session State
給 Widget 一個 key,它的值會自動進 st.session_state:
同一個頁面上,相同參數的 Widget 必須有不同 key,否則 Streamlit 無法分辨它們。
按鈕的陷阱
st.button() 只有在「這一次重跑是因為按了它」時才是 True。下一輪互動又會變回 False。所以計數、多步驟流程不要只靠 if st.button(...) 裡的區域變數,要寫進 Session State。