Is there an easy way to change the Toggle message after Toggling?

I am running Streamlit locally using streamlit version 1.30.0 and python version 3.9.18

I have a toggle button where I want the message to say “Inclusive search (or)” when the toggle is true and “Exclusive search (and)” when the toggle is false.

I originally tried using st.session_state similar to this post: Changing text of button - #3 by minhanh29
but I found that either any button click on the page would cause it to toggle or it would only toggle once and be stuck in that state.

I also tried to use the on_change variable similar to described here:

but again I ran into issues.

I finally settled on the following solution:

import streamlit as st

col1, col2 = st.columns([1, 35])
show_all  = col1.toggle(" ", value=True)
if show_all:
    col2.write(f'Inclusive Search (or)')
else:
    col2.write(f'Exclusive search (and)')

However, if the window gets resized at all the columns look weird and this is definitely a workaround situation. Is there a better way to do this???

I’d make the label in the toggle a variable:

dnamic_toggle

import streamlit as st

toggle_label = (
    "The toggle is ON"
    if st.session_state.get("my_toggle", False)
    else "The toggle is OFF"
)
toggle_value = st.session_state.get("my_toggle", False)

is_toggle = st.toggle(toggle_label, value=toggle_value, key="my_toggle")
st.info(f"The toogle is {is_toggle}")

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