Help Request - st.Button is clearing screen

Summary

I added a sidebar this morning to this app and now when I run the main function it clears the screen instead of outputting the expected values.

Code snippet:

import streamlit as st

st.set_page_config(
    page_title="SQL Formatter",
    page_icon=":shark:"
)


def column_formatter():
    def format_sql(value):
        return ", ".join(repr(s) for s in value.split("\n"))

    st.header("Column Formatter")
    value = st.text_area('Enter the data you wish to modify', height=500)

    if st.button('Modify'):
        st.write(format_sql(value))


st.sidebar.markdown('''
            <style>
            .css-1ope8sv.e1fqkh3o4 {text-align: center;}
            .css-1ope8sv.e1fqkh3o4 h2 {padding-bottom: 2em;}
            </style>
            ''', unsafe_allow_html=True)
st.sidebar.header('SQL Utilities Menu')
if st.sidebar.button(label='Column Formatter'):
    column_formatter()

Expected behavior:

When clicking on Column Formatter it will run the appropriate function. I can paste the values but when I click ‘Modify’ and it runs format_sql() it clears the screen instead of outputting the values. I found that if I remove the sidebar entirely from the code it works again.

Debug info

  • Python version: 3.10
  • VS Code
  • OS version: Windows 11
  • Browser version: Firefox

There’s some trickiness in using a button to open something, because a button doesn’t have state – if it’s pressed once, the next time you run the script it doesn’t automatically remember that it was previously pressed. One workaround is to use session_state to make the button effectively work like a toggle.

st.sidebar.header("SQL Utilities Menu")
if "open_formatter" not in st.session_state:
    st.session_state["open_formatter"] = False

if st.sidebar.button(label="Column Formatter"):
    # Every time the button is pressed, flip the session state to the opposite value
    st.session_state["open_formatter"] = not st.session_state["open_formatter"]

if st.session_state["open_formatter"]:
    column_formatter()

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