Incorporate Input with Tabs

Hello, I’m trying to have some inputs at tabs. However, even though I’m at the first tab, the code also runs the second tab and replaces the value get from the first tab. I’m aware that Streamlit doesn’t support conditional render yet. Any solution or better approach?

import streamlit as st

tabs = st.tabs(['Addition', 'Multiplication'])

with tabs[0]:
    x = st.number_input('first number', 0, key='first_tab_first_number')
    y = st.number_input('second number', 0, key='first_tab_second_number')
    result = x + y

with tabs[1]:
    x = st.number_input('first number', 0, key='second_tab_first_number')
    y = st.number_input('second number', 0, key='second_tab_second_number')
    result = x * y

st.write(result) # This will always show result from tabs[1] even though I open / modified tabs[0]

You should wrap each tab group in a form. Tabs are simply a UI layout mechanism. In your case the final bound value for result will always be written.

1 Like

An option is the tab_bar component from the extra_streamlit_components package (extra-streamlit-components · PyPI) to get that conditional behavior for tabs. Also, imo they look prettier than st.tabs.

stxExample

import streamlit as st
import extra_streamlit_components as stx

tab = stx.tab_bar(data=[
    stx.TabBarItemData(id="add", title="➕ Addition", description="Add two numbers"),
    stx.TabBarItemData(id="mult", title="✖ Multiplication", description="Multiply two numbers")])

if tab == "add":
    x = st.number_input('first number', 0, key='first_tab_first_number')
    y = st.number_input('second number', 0, key='first_tab_second_number')
    result = x + y

elif tab == "mult":
    x = st.number_input('first number', 0, key='second_tab_first_number')
    y = st.number_input('second number', 0, key='second_tab_second_number')
    result = x * y

else: 
    result = "Select an option first"

st.write(f"# The result is {result}")
st.warning("""`pip install extra_streamlit_components`""")
1 Like

Another great option for tabs is the option bar available at hydralit-components · PyPI

Cheers

1 Like

Thank you, this is very helpful :laughing: