嵌套按钮的 Streamlit 会话状态

问题描述 投票:0回答:2

我正在尝试使用streamlit中的会话状态来创建一个两个嵌套按钮,其中第一个按钮单击显示推荐的电影,第二个提交按钮提交用户的评论,其中情绪分析模型正在工作。但嵌套按钮需要会话状态,所以我尝试了会话状态,但总是出错。下面是代码。

if 'rec_btn' not in st.session_state:
        st.session_state.rec_btn= False
    
    def callback():
        st.session_state.rec_btn = True
    
    if st.button('RECOMMEND',key = 'rec_btn'):
      col1, col2, col3 = st.columns(3)
     
      with col1:
          st.image(output_images[0])
          st.markdown(output_names[0].upper())
          review = st.text_input(f"How much you liked the movie {output_names[0]}")
          if st.button('submit',on_click=callback):
                review = re.sub('[^a-zA-Z0-9 ]','',review)
                review = tf_idf_vectorizer.transform([review])
                ans = model_sentiment.predict(review)
                if  ans == 0:
                    review = 'Thanks for your positive review'
                else:
                    review = 'Sorry for your negative review'
                st.write(review)

我总是遇到错误:

StreamlitAPIException: Values for st.button, st.download_button, st.file_uploader, 
and st.form cannot be set using st.session_state.
python frameworks session-state streamlit
2个回答
3
投票

问题在于我如何使用按钮的会话状态。我可以使用下面的代码来理解这一点。这样嵌套按钮就可以一起工作了。

import streamlit as st
button1 = st.button('Recommend')
if st.session_state.get('button') != True:

    st.session_state['button'] = button1 # Saved the state

if st.session_state['button'] == True:

    st.write("button1 is True")

    if st.button('Check 2'):

        st.write("Do your logic here")

0
投票

我不确定为什么会出现这种情况,但我仅使用带有键文字字符串的按钮就遇到了这个确切的错误。该密钥没有在其他地方使用,并且与会话状态无关。简而言之,这失败了:

if button("okay", key="dialog"):
    # doesn't matter what I do here - that line throw an exception

StreamlitAPIException: Values for st.button, st.download_button, st.file_uploader, and st.form cannot be set using st.session_state.

在哪里效果很好:

if button("okay"):
    # no key, no problem?!

讨厌给出一个我没有解释的答案 - 但万一你最终来到这里,它可能会为你省去一些麻烦。

© www.soinside.com 2019 - 2024. All rights reserved.