Any workaround for placeholder of interactive widget?

Hi,

I’m trying to find any workaround to the problem that one can’t use a placeholder for interactive widgets.
for example: st.number_input

When I press a button widget, I want the option to clear the widget from the screen.

Blockquote

import streamlit as st
import numpy as np

if ‘flag’ not in st.session_state:
st.session_state.flag = 0

if st.session_state.flag ==0:
n = st.number_input(“enter number:”,1,10,4)

if st.button(“random plot”):
st.session_state.flag =1
st.bar_chart(np.random.randn(50, 3))

Blockquote

So, when I hit the ‘random plot’ button, I want to remove the input widget from the UI.
I understand that this is a problem, but I was wondering if anyone knew of a workaround or had any ideas on how to solve it.

Thanks in advance :slight_smile:

Hi @ori, :wave:

You can actually use st.empty() to create a placeholder for the number input widget, which you can then clear after a button click.

Here’s how:

import streamlit as st
import numpy as np

# Function to clear the number input widget
def clear_number_widget(widget):
    widget.empty()

# Insert a single element container
placeholder = st.empty()

if 'flag' not in st.session_state:
    st.session_state.flag = 0

if st.session_state.flag ==0:
    # Use the placeholder container to hold a number input widget
    n = placeholder.number_input("enter number:",1,10,4)

if st.button("random plot"):
    st.session_state.flag =1
    # Clear the number input widget
    clear_number_widget(placeholder)
    st.bar_chart(np.random.randn(50, 3))

Output:
clear-number-input

Does this help?

Happy Streamlit-ing! :balloon:
Snehan

2 Likes

Thanks Snehan. Great solution :slight_smile:

1 Like

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