Display images one by one with a next button

I have a streamlit code snippet below, where I iterate through a folder to display all the images there.

if st.button("Display images with PII"):
        out_folder = "output"
        for i in os.listdir(out_folder):
            if i.endswith(("jpg", "jpeg", "png")):
                image = Image.open(os.path.join(out_folder, i))
                st.image(image, caption=i)

However, I do not want to display all the images at one go, but rather one image at a time, preferably with a “Next” button to show the next image. Is this possible?

2 Likes

I’ve been looking for something similar for days. How to show the images incrementally and not all at once. I have an application and sometimes need to show hundreds of images as the result of an action. But displaying those images takes a lot of time and impacts usability.
Is there anyway to be able to load the images incrementally, either by pushing a button (for instance, “show next 20 images”), or showing the images in multiple pages (for instance, something like this: First … 5 6 7 8 … Last)

Probably not the best approach but here is an idea using a session_state parameter as a counter:

cyclephoto

Code:

import streamlit as st
import os

col1,col2 = st.columns(2)

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

def showPhoto(photo):
    col2.image(photo,caption=photo)
    col1.write(f"Index as a session_state attribute: {st.session_state.counter}")
    
    ## Increments the counter to get next photo
    st.session_state.counter += 1
    if st.session_state.counter >= len(pathsImages):
        st.session_state.counter = 0

# Get list of images in folder
folderWithImages = r"images"
pathsImages = [os.path.join(folderWithImages,f) for f in os.listdir(folderWithImages)]

col1.subheader("List of images in folder")
col1.write(pathsImages)

# Select photo a send it to button
photo = pathsImages[st.session_state.counter]
show_btn = col1.button("Show next pic ⏭️",on_click=showPhoto,args=([photo]))
2 Likes

Thanks @edsaac

Using your example I was able to build the functionality that I was looking for. I’m still curious to know whether there is a recommended approach which is supported natively by streamlit, or if they’re working on that.

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