Streamlit widget dependency

I am trying a simple concept of two widgets, where one is dependent on the other

I want to user to click a button, that opens up a number slider. The user then has the option to select the number through the number slider.

Here is the code I am using:

    import streamlit as st
    press_button = st.button("Press it Now!")
    if press_button :
        # ask for the value
        th = st.number_input("Please enter the values from 0 - 10",)

The issue I face is the moment I change the number sliderā€™s value, streamlit reruns the entire thing, and one has to push the ā€œbuttonā€ again to get back to the number slider. Ultimately, the number slider never changes

Hello @fahadakbar,
Yeah, even I had to face problems like this. However, instead of using a button, I used a checkbox. The thing is - st.button() returns a boolean value ryt. So now only when it is true, it is going to display the st.number_input(). Therefore, when you enter a number, that press_button becomes false as you did not press it. That is why it happens.
Personally, I just used a checkbox and that solved the problem for me.
If there is a way around that without using checkbox, even I would love to know.
Anyways, try checkbox and see.

import streamlit as st
    press_button = st.checkbox("Press it Now!")
    if press_button :
        # ask for the value
        th = st.number_input("Please enter the values from 0 - 10",)

Regards,
Amaan

1 Like

Thank you so much Amaan, this workaround was successful!

1 Like

This leaves me a question though,

when and why would you use a ā€œbuttonā€?

:slight_smile:

@fahadakbar
There are many uses of st.button().

  1. Letā€™s say that you built a ML model and user inputs several fields. Then the user can press a button (ā€˜Predictā€™) and your app can display the predicted output (st.success()).
  2. You want to visualize and after entering the fields, press (ā€˜Visualizeā€™) and so on.

Like this, there can be may combinations. It all depends on the architecture of your app i.e. how you want to use a specific widget or what you want to do with it etc. Hence, choose a component or widget based on the workflow of your app.

Cheers :+1:!
Amaan

@amaan_142

letā€™s say I have a predict button, and ask for the data from the user as an input
wouldnā€™t pressing the button means that the user will need to give me data again?

@fahadakbar
Check this example (Screenshots in the readme file). This is what I was talking about.

If you implement the session state or url get/set query parameters, you can maintain a ā€œbutton pushedā€ flag which will allow you to persist the button pushed state across runs.

1 Like