顯示下載按鈕小部件。
當您希望為用戶提供一種直接從您的應用下載文件的方式時,這很有用。
請注意,要下載的數據在用戶連接時存儲在內存中,因此最好將文件大小保持在幾百兆字節以下以節省內存。
函數簽名
st.download_button(label, data, file_name=None, mime=None, key=None, help=None, on_click=None, args=None, kwargs=None, *, disabled=False)
參數 | 說明 |
---|---|
label (str) | 一個簡短的標簽,向用戶解釋此按鈕的用途。 |
data (str or bytes or file) | 要下載的文件的內容。請參閱下麵的示例以了解緩存技術以避免不必要地重新計算此數據。 |
file_name (str) | 用作要下載的文件名的可選字符串,例如'my_file.csv'。如果未指定,將自動生成名稱。 |
mime (str or None) | 數據的 MIME 類型。如果為 None,則默認為 "text/plain"(如果數據類型為 |
key (str or int) | 一個可選的字符串或整數,用作小部件的唯一鍵。如果省略,將根據其內容為小部件生成一個 key 。相同類型的多個小部件可能不共享相同的鍵。 |
help (str) | 將鼠標懸停在按鈕上時顯示的可選工具提示。 |
on_click (callable) | 單擊此按鈕時調用的可選回調。 |
args (tuple) | 傳遞給回調的可選參數元組。 |
kwargs (dict) | 一個可選的 kwargs 字典傳遞給回調。 |
disabled (bool) | 一個可選的布爾值,如果設置為 True,則禁用下載按鈕。默認值為假。此參數隻能由關鍵字提供。 |
返回 | 說明 |
(bool) | 如果在應用程序的最後一次運行中單擊了按鈕,則為 True,否則為 False。 |
例子
以 CSV 格式下載大型 DataFrame:
@st.cache
def convert_df(df):
# IMPORTANT: Cache the conversion to prevent computation on every rerun
return df.to_csv().encode('utf-8')
csv = convert_df(my_large_df)
st.download_button(
label="Download data as CSV",
data=csv,
file_name='large_df.csv',
mime='text/csv',
)
將字符串下載為文件:
text_contents = '''This is some text'''
st.download_button('Download some text', text_contents)
下載二進製文件:
binary_contents = b'example content'
# Defaults to 'application/octet-stream'
st.download_button('Download binary file', binary_contents)
下載圖像:
with open("flower.png", "rb") as file:
btn = st.download_button(
label="Download image",
data=file,
file_name="flower.png",
mime="image/png"
)
相關用法
- Python Streamlit st.dataframe用法及代碼示例
- Python Streamlit st.date_input用法及代碼示例
- Python Streamlit st.experimental_singleton.clear用法及代碼示例
- Python Streamlit st.bokeh_chart用法及代碼示例
- Python Streamlit st.caption用法及代碼示例
- Python Streamlit st.text_input用法及代碼示例
- Python Streamlit st.area_chart用法及代碼示例
- Python Streamlit st.title用法及代碼示例
- Python Streamlit st.cache用法及代碼示例
- Python Streamlit st.experimental_singleton用法及代碼示例
- Python Streamlit st.empty用法及代碼示例
- Python Streamlit st.error用法及代碼示例
- Python Streamlit st.video用法及代碼示例
- Python Streamlit st.vega_lite_chart用法及代碼示例
- Python Streamlit st.slider用法及代碼示例
- Python Streamlit st.header用法及代碼示例
- Python Streamlit st.container用法及代碼示例
- Python Streamlit st.form_submit_button用法及代碼示例
- Python Streamlit st.form用法及代碼示例
- Python Streamlit st.plotly_chart用法及代碼示例
- Python Streamlit st.bar_chart用法及代碼示例
- Python Streamlit st.code用法及代碼示例
- Python Streamlit st.experimental_memo.clear用法及代碼示例
- Python Streamlit st.warning用法及代碼示例
- Python Streamlit st.image用法及代碼示例
注:本文由純淨天空篩選整理自streamlit.io大神的英文原創作品 st.download_button。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。