Streamlit运行时选择other选项后无法显示新增文本输入框的问题
问题:选择'other'选项时文本输入框无法显示
在运行Streamlit代码时,当在topic下拉选择框中选择'other'选项,期望出现的文本输入框无法正常显示。原代码如下:
import streamlit as st import emailing st.session_state['topic'] = None with st.form(key='email'): user_email = st.text_input('Enter your email:', key='email') about = st.selectbox('what do you wanna discuss', options=('job', 'projects', 'salary', 'other'), key='topic') if about == 'other': other_about = st.text_input('what do you wanna discuss about') message = st.text_area('message', key='message') button = st.form_submit_button('submit') string = f""" subject: NEW ONE from {user_email} TOPIC: {about} {message} """ if button: emailing.send(string) st.info('success')
问题原因
手动设置st.session_state['topic'] = None会在每次页面刷新(包括下拉框选项变更时)重置topic的状态值,干扰了Streamlit对组件状态的自动跟踪,导致if about == 'other'的判断逻辑无法正确触发,从而无法渲染对应的文本输入框。
修复方案
删除手动修改session_state的代码,让Streamlit自动管理下拉框的状态。同时如果需要将'other'对应的输入内容加入邮件,可将其整合到邮件文本中。
修复后的代码:
import streamlit as st import emailing with st.form(key='email'): user_email = st.text_input('Enter your email:', key='email') about = st.selectbox('what do you wanna discuss', options=('job', 'projects', 'salary', 'other'), key='topic') # 初始化变量避免未定义报错 other_about = "" if about == 'other': other_about = st.text_input('what do you wanna discuss about', key='other_topic') message = st.text_area('message', key='message') button = st.form_submit_button('submit') # 根据选项拼接主题内容 topic_content = about if about != 'other' else f"{about}: {other_about}" string = f""" subject: NEW ONE from {user_email} TOPIC: {topic_content} {message} """ if button: emailing.send(string) st.info('success')
内容的提问来源于stack exchange,提问作者grebtor
相关产品推荐
相关产品推荐

