我在我的流光应用程序的侧边栏中有一个多选择框。不丧失一般性:
1
和2
因此,如果选择了2
,我想从可能的选择列表中删除1
,但streamlit似乎没有这样的能力,所以我尝试将它封装在一个循环中,这个循环也失败了(DuplicateWidgetID: There are multiple identical st.multiselect widgets with the same generated key.
):
options = [1,2,3,4,5,6,7,8,9,10]
space = st.sidebar.empty()
answer, _answer = [], None
while True:
if answer != _answer:
answer.append(space.multiselectbox("Pick a number",
options,
default=answer
)
)
options = [o for o in options if o not in answer]
if 1 in options:
if 2 in options: options.remove(2)
if 2 in options:
if 1 in options: options.remove(1)
_answer = answer[:]
对我如何做到这一点有什么想法吗?
发布于 2022-05-15 00:25:55
方法1
这里有一种方法,提供有关小部件的帮助,只允许用户同时选择1和2,但如果两者都被选中,则必须筛选出2。然后,您可以只使用经过验证的选择。
代码
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))
输出
将鼠标悬停在?
上以显示帮助。
方法2
选项1或2使用单选按钮,对multiselect使用其余选项。
代码
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))
输出
方法3
选择1时,删除2,然后重新运行以更新选项。同样,当选中2时,删除1并重新运行以更新选项。
代码
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))
输出
https://stackoverflow.com/questions/64449305
复制相似问题