Variable update in for cycle

In main_page_c.container, why i is always 1 and results is always “RESIZER”?
“results” in tabs_container is expected, but not expected in maint_page_c.

import streamlit as st

tab_list=["LOAD","RESIZER"]
tabs_container= st.tabs(tab_list)
main_page_c = st.empty()

for i in range(0,len(tab_list)):
    with tabs_container[i]:
        results=tab_list[i]
        st.write(results)
        with main_page_c.container():
             st.write(results)
             st.write(i)

This is because tabs are merely a visual presentation element currently, and they don’t change when code runs. When you loop through your tabs, all of the code for all of the tabs gets run. The outputs don’t get displayed until you click on a tab, but the code has already been run. This means that main_page_c first gets LOAD, 0 written, and then that gets overwritten with RESIZER, 1.

Unfortunately, I can’t think of a good way to accomplish what you’re trying to do with st.tabs. There are a number of widgets you could use as an alternative if you want to overwrite the container contents depending on the selection (e.g. st.selectbox).

This accomplishes something similar to what you were looking for, I believe.

import streamlit as st

tab_list = ["LOAD", "RESIZER"]
selected_tab = st.selectbox("Select tab", tab_list)
main_page_c = st.empty()

i = tab_list.index(selected_tab)
results = tab_list[i]
st.write(results)
with main_page_c.container():
    st.write(results)
    st.write(i)

Thanks for help!
And I have another question, how to increase option value every time when I press button?
It is a simplified problem. Seems, code is rerun when I press button, so option value is always 1.

import streamlit as st
option=0
st.write(option)
if(st.button("add_option")):    
    option=option+1
    st.write("option_value:"+str(option))

That’s a classic use-case for st.session_state

import streamlit as st

if "option" not in st.session_state:
    st.session_state["option"] = 0

st.write(st.session_state["option"])

if(st.button("add_option")):
    st.session_state["option"] += 1
    st.write("option_value:", st.session_state["option"])
1 Like

Got it, hanks for help!

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.