簡體   English   中英

Select Streamlit 中復選框中的多個選項

[英]Select multiple options in checkboxes in Streamlit

我是 Streamlit 的新手。 我想進行多項選擇用戶輸入(復選框)。 但我想 select 最多 4 個選項中的 3 個選項。

我嘗試過使用multiselect的下拉功能。

import streamlit as st
option = st.multiselect('Select three known variables:', ['initial velocity (u)', 'final velocity (v)', 'acceleration (a)', 'time (t)'])  

有用。 但我認為這對我的情況來說不是用戶友好的。 此外,在這里我無法將選擇限制為 4 個中的 3 個。用戶可以在這里 select 所有 4 個選項。 但我想要這樣的代碼,如果選擇了第 4 個,那么之前的選擇(第 3 個選項)將自動取消選擇。 我更喜歡復選框的外觀,例如radio按鈕:

import streamlit as st
option = st.radio('Select three known variables:', ['initial velocity (u)', 'final velocity (v)', 'acceleration (a)', 'time (t)'])  

但是使用radio ,我不能 select 多個選項。 如何編輯它以便我可以將其顯示為復選框並且只能選擇 3 個選項?

這在視覺上最接近您想要的,因為它們實際上是復選框,而不是單選按鈕。 但是您不能限制選定的選項,因此可以檢查所有選項。

st.write('Select three known variables:')
option_1 = st.checkbox('initial velocity (u)')
option_2 = st.checkbox('final velocity (v)')
option_3 = st.checkbox('acceleration (a)')
option_4 = st.checkbox('time (t)')

在此處輸入圖像描述

作為一種解決方法,您可以通過以下方式使用單選按鈕,因為它們只允許檢查一個組合:

option = st.radio('Select three known variables:',
                  ['initial velocity (u), final velocity (v), acceleration (a)',
                   'initial velocity (u), final velocity (v), time (t)',
                   'initial velocity (u), acceleration (a), time (t)',
                   'final velocity (v),acceleration (a), time (t)'])

在此處輸入圖像描述

我還沒有找到任何能正確滿足我需求的streamlit function。 因此,我按照anilewe的建議使用 function streamlit.checkbox並添加一些額外的條件語句,以便用戶必須 select 任意 3 個復選框。 這是我的代碼:

import streamlit as st
st.write('Select three known variables:')
option_s = st.checkbox('displacement (s)')
option_u = st.checkbox('initial velocity (u)')
option_v = st.checkbox('final velocity (v)')
option_a = st.checkbox('acceleration (a)')
option_t = st.checkbox('time (t)')
known_variables = option_s + option_u + option_v + option_a + option_t

if known_variables <3:
    st.write('You have to select minimum 3 variables.')
elif known_variables == 3:
   st.write('Now put the values of your selected variables in SI units.')
else:
    st.write('You can select maximum 3 variables.')

更新:創建字典可以更加自動化和有用; 在將方法從st.checkbox更改為其他方法的情況下也很有幫助:

import streamlit as st
st.write('Select three known variables:')
opts = [ ('s', 'displacement'), ('u', 'initial velocity'), ('v', 'final velocity'), ('a', 'acceleration'), ('t', 'time') ]
known_variables = {symbol: st.checkbox(f"{name} ({symbol})") for symbol, name in opts}    

if sum(known_variables.values()) < 3:
    st.write('You have to select minimum 3 variables.')
elif sum(known_variables.values()) == 3:
    st.write('Now put the values of your selected variables in SI units.')
else:
    st.write('You can select maximum 3 variables.')

盡管如此,我還是希望得到一個 function,它看起來像checkboxradio按鈕,但具有限制特定選擇數量的內置功能。 總之,我認為我想要的 function 可以稱為“多選收音機”。 因此,我不會將附加條件限制在我自己的限制選擇上。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM