How do I replace an image I'm showing using st.image() in the same place?

Summary

I show an image that I want to show on the screen with st.image(). How can I change the image inside st.image() when I press a button?

Steps to reproduce

Code snippet:

add code here

If applicable, please provide the steps we should take to reproduce the error or specified behavior.

Expected behavior:

Explain what you expect to happen when you run the code above.

Actual behavior:

Explain the undesired behavior or error you see when you run the code above.
If you’re seeing an error message, share the full contents of the error message here.

Debug info

  • Streamlit version: (get it with $ streamlit version)
  • Python version: (get it with $ python --version)
  • Using Conda? PipEnv? PyEnv? Pex?
  • OS version:
  • Browser version:

Requirements file

Using Conda? PipEnv? PyEnv? Pex? Share the contents of your requirements file here.
Not sure what a requirements file is? Check out this doc and add a requirements file to your app.

Links

  • Link to your GitHub repo:
  • Link to your deployed app:

Additional information

If needed, add any other context about the problem here.

Here is one approach. Save your image filenames in a list. We will use session state variable as index into that list.

import streamlit as st


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

IMAGES = ['aaa.jpg', 'bbb.jpg']

def change():
    st.session_state.idx += 1
    if st.session_state.idx >= len(IMAGES):
        st.session_state.idx = 0

# Show image by images index.
st.image(IMAGES[st.session_state.idx])
st.button('Next image', on_click=change)
1 Like

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