Combination of Drop-down menu (st.selectbox) with a Button (st.Button) to control execution flow doesn't work 💥

Steps to replicate problem:

  1. Go to main app website -
  2. Select “Gradient Descent” as the linear regression method in step 4 and press “Predict” Button
    Note: "Predict" st.button works fine for all the other options in the dropdown
  3. Once you’re in Gradient Descent, you can update the sliders as you wish and select Plotting/Animation method.
  4. PROBLEM STARTS HERE - Once you select any of the options in the 2nd and hit Go, it brings you back to step 3 without anything else happening

Checked-in code in Github here - (see elif lira_method == "Gradient Descent": which essentially implements the Gradient Descent dropdown in Step 3.

In my local sandpit, I’ve also tried removing the st.button(Go) and strangely this happens:

  • Code runs straight-through for the first option in the mode = st.selectbox("Select Plotting Library",('Skip Animation','Matplotlib','Plotly','Altair'))
  • If I re-arrange the options and set, say, Matplotlib first, it will run the animation without any issues. The same with Plotly or Altair. If they’re first in the st.selectbox statement code runs and I get the correct error message.
  • But if I select any other method other than the first one in the st.selectbox statement, it takes me to Step 3.

I hope it’s not a schoolboy error with the if/elif statements but any help would be appreciated as I’m stuck for days. :frowning:

What you need is this:

That is, store the button pressed state in a session state and use that for your further steps (say step-3).

The problem occurs because when you press a button in step-2, it will be marked as true only during the first refresh. When you change anything beyond that, the subsequent refresh will return false for the button pressed state.

1 Like

Oh thank you @GokulNC.

Makes so much sense now. I’ve spent so much time trying to debug it by adding messages to print in various stages that it’s a bit of a relief to find out it’s not me :slight_smile:

Ok cool, I’ll take a look at the other thread and update my code.

Thank you for the help. :pray: