我编写了一些虚拟代码来复制我的问题。我需要在Streamlit中做一些简单的计算,但我似乎找不出它们是如何处理变量和如何存储信息的,这就是我的例子:
import streamlit as st
sidebarOption = st.sidebar.radio('Options',("A","B","C"))
if sidebarOption == 'A':
param1 = st.number_input('Value 1', min_value=1.0, max_value=100.0, value =20.0, step=0.1 )
param2 = st.number_input('Value 2', min_value=1.0, max_value=50.0, value =24.0, step=0.1 )
elif sidebarOption == 'B':
param3 = st.number_input('Value 3', min_value=1.0, max_value=100.0, value =20.0, step=0.1 )
param4 = st.number_input('Value 4', min_value=1.0, max_value=50.0, value =24.0, step=0.1 )
elif sidebarOption == 'C':
add = param1+param3
st.write('Add:', add)我知道错误:
NameError: name 'param1' is not defined我做错了什么?
发布于 2022-07-05 13:31:53
这个问题与Streamlit无关,只是没有定义变量。让我在没有Streamlit部分的情况下重写您的代码,并添加注释,看看这是否澄清了一些事情:
option = 'C'
if option == 'A':
foo = 1 # this line is not executed, since option is not A
elif option == 'B':
bar = 2 # this line is not executed, since option is not B
elif option == 'C':
# the code below is executed, but foo and bar are undefined, so there is an error
baz = foo + bar
print(baz)这个错误更有意义吗?如果您想要添加foo和bar,必须首先定义它们,这不是这里的情况。
如果您确信在选项C之前使用选项A和B调用代码,那么它应该可以工作。但是,最好事先设置一些默认值,比如foo = None和bar = None。如果在C步骤中仍然没有错误,您仍然会得到一个错误,但是这会更清楚。
或者你要找的是会话状态
发布于 2022-07-05 14:51:07
会话状态工作。不知道它是否100%正确,但这适用于一个小型测试示例:
import streamlit as st
from streamlit_option_menu import option_menu
"st.session_state object", st.session_statewith st.sidebar:
selected = option_menu(
menu_title= "Exposure time calculator",
options=['A', 'B', 'C'],
)
if selected == 'A':
param1 = st.number_input('val1', value=20.0, key='key1')
param2 = st.number_input('val2', value = 30.0, key = 'key2')
elif selected == 'B':
add = st.session_state.key1 + st.session_state.key2
divide = st.session_state.key1/st.session_state.key2
st.write(add)
st.write(divide)https://stackoverflow.com/questions/72868388
复制相似问题