Using Streamlit:Problems with using the button and selectbox widgets

I had some problems using these widgets. My function: Click the Start button, the content in the red box below appears, but when click the drop-down box to select the data, the content in the red box will disappear, only the Start button in the initial state. Why is this happening? What should be done?

import streamlit as st
if st.button('开始'):
  opt = st.selectbox('测试', options=['测试数据1','测试数据2','测试数据3','测试数据4'])
  if opt: st.write(f"选中的数值为: {opt}")

Welcome!!

That behavior is normal. Have a look on how to use a button effectively.

It is also connected to the main concept of streamlit specially on Data Flow.

What happen is after a button is hit, its value is set to true. Streamlit rerun the code from top to bottom, check if button is hit (true) and read the next code, hitting the selectbox. However after selection, streamlit reruns the code from top to bottom again, passing thru the if st.button() and unfortunately the value of the button is now false. So it cannot enter the selectbox.

There is a search button at the top-right of this page, use it to search similar topics and how they solve it.

image

Do you have a specific solution?Please

Streamlit provides a means to store variables in session_state. Once we press that button, we have to store a true value in this variable.

if 'btn' not in st.session_state:
    st.session_state.btn = False

Our variable name is st.session_state.btn and has a value of False initially. Once the button is clicked, we will store into it a True value.

if st.button('开始'):
    st.session_state.btn = True

Now we can always access the selectbox using our variable.

if st.session_state.btn:
    opt = st.selectbox('测试', options=['测试数据1','测试数据2','测试数据3','测试数据4'])
    if opt: st.write(f"选中的数值为: {opt}")

Full code

import streamlit as st

if 'btn' not in st.session_state:
    st.session_state.btn = False

if st.button('开始'):
    st.session_state.btn = True

if st.session_state.btn:
    opt = st.selectbox('测试', options=['测试数据1','测试数据2','测试数据3','测试数据4'])
    if opt: st.write(f"选中的数值为: {opt}")

Thank you for your solution, the problem has been successfully solved.