环境变量

neevop 十二月 3, 2023

st.session_state

import streamlit as st

# Initialization
if 'key' not in st.session_state:
    st.session_state['key'] = 'value'

# Session State also supports attribute based syntax
if 'key' not in st.session_state:
    st.session_state.key = 'value'
   
st.write(st.session_state.key)
  
st.session_state.key = 'value2'     # Attribute API
st.session_state['key'] = 'value2'  # Dictionary like API

st.session_state
st.write(st.session_state['value2'])

每个带有键的小部件都会自动添加到会话状态:

st.text_input("Your name", key="name")

# This exists now:
st.session_state.name

回调

回调是一个 Python 函数,当输入小部件发生更改时会调用该函数。当响应事件更新Session状态时,首先执行回调函数,然后从上到下执行应用程序。on_change并且on_click事件仅在输入类型小部件上受支持。

def form_callback():
    st.write(st.session_state.my_slider)
    st.write(st.session_state.my_checkbox)

# 只有st.form_submit_button表单中有回调。表单内的其他小部件不允许有回调。
with st.form(key='my_form'):
    slider_input = st.slider('My slider', 0, 10, 5, key='my_slider')
    checkbox_input = st.checkbox('Yes or No', key='my_checkbox')
    submit_button = st.form_submit_button(label='Submit', on_click=form_callback)

st.set_page_config

配置页面的默认设置,并且每个页面只能设置一次。

# st.set_page_config(page_title=None, page_icon=None, layout="centered", initial_sidebar_state="auto", menu_items=None)
import streamlit as st

st.set_page_config(
    page_title="Ex-stream-ly Cool App",
    page_icon="🧊",
    layout="wide",
    initial_sidebar_state="expanded",
    menu_items={
        'Get Help': 'https://www.extremelycoolapp.com/help',
        'Report a bug': "https://www.extremelycoolapp.com/bug",
        'About': "# This is a header. This is an *extremely* cool app!"
    }
)