1 回答

TA貢獻(xiàn)1817條經(jīng)驗 獲得超6個贊
方法一
這是一種方法,在小部件上提供幫助,只允許用戶選擇 1 和 2,但如果兩者都被選擇,我們必須過濾掉 2。然后您就可以使用經(jīng)過驗證的選擇。
代碼
import streamlit as st
ms = st.sidebar.multiselect('Pick a number', list(range(1, 11)),
help='Choose either 1 or 2 but not both. If both are selected 1 will be used.')
if 1 in ms and 2 in ms:
ms.remove(2)
st.write('##### Valid Selection')
st.write(str(ms))
輸出
將鼠標(biāo)懸停在 上?可顯示幫助。
方法二
使用單選按鈕選擇選項 1 或 2,其余選項用于多選。
代碼
import streamlit as st
rb = st.sidebar.radio('Pick a number', [1, 2])
ms = st.sidebar.multiselect('Pick a number', list(range(3, 11)))
selected = ms
selected.append(rb)
st.write('##### Valid Selection')
st.write(str(selected))
輸出
方法三
選擇 1 后,刪除 2,然后重新運(yùn)行以更新選項。同樣,當(dāng)選擇 2 時,刪除 1 并重新運(yùn)行以更新選項。
代碼
import streamlit as st
init_options = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
if 'options' not in st.session_state:
st.session_state.options = init_options
if 'default' not in st.session_state:
st.session_state.default = []
ms = st.sidebar.multiselect(
label='Pick a number',
options=st.session_state.options,
default=st.session_state.default
)
# If 1 is selected, remove the 2 and rerun.
if 1 in ms:
if 2 in st.session_state.options:
st.session_state.options.remove(2)
st.session_state.default = ms
st.experimental_rerun()
# Else if 2 is selected, remove the 1 and rerun.
elif 2 in ms:
if 1 in st.session_state.options:
st.session_state.options.remove(1)
st.session_state.default = ms
st.experimental_rerun()
st.write('##### Valid Selection')
st.write(str(ms))
輸出
添加回答
舉報