Radio Button refreshing page

Hi, Iโ€™m currently new to using streamlit/python and currently having issues with radio buttons refreshing the page when pressed. It could be me not understanding whats happening in the background.

I want to create a button asking the user if the generated python code is correct before running it.
Iโ€™ve tried using radio buttons for this but whenever a button is pressed it refreshes the page and clears the code / question.

Iโ€™m also running this locally.

Is there anyway to do this ?

if question := st.chat_input('What python code do you want to generate?'):
    with st.chat_message('user'):
         st.write(question)
    python_code = generate_python_code(my_question)
    with st.chat_message('assistant'):
        st.code(python_code, language='python', line_numbers=True)
        options = [' ', 'yes', 'no']
        radio_python = st.radio('Are you happy with the python code', options=options, index=0)

       if radio_python == 'yes':
            result_code = run_python_code(python_code)
            st.write(result_code)

        elif radio_python == 'no':
            python_code_resp = code_editor(python_code, lang="python")
            fixed_python_code = python_code_resp["text"]

            if fixed_python_code != "":
                result_code = run_python_code(fixed_python_code)
                st.write(result_code)
            else:
                python_code = None
                st.write('No Python Code')
        else:
             python_code = None
             st.write('No Python Code')

This is expected behavior for Streamlit: When a user interacts with a widget, the whole page is rerun. The rerun is how the widget is able to output the new selection.

Option 1: You can save the question and answer in Session State so that you can retrieve it on successive reruns. This is the basic pattern for chat apps.

Option 2: If you donโ€™t want to deal with anymore than a single question and response, you could put the survey-like question in a fragment so any question you ask about the content above is contained within a smaller rerun scope.

1 Like