[Python] How to change and load a png file without refreshing the app?

Discussão em 'Python' iniciado por Stack, Julho 31, 2025.

  1. Stack

    Stack Membro Participativo

    I have a Shiny for Python app which displays an image. Whenever I regenerate the image from within the app, the entire app reloads, losing the input settings (the slider value resets). Is there a way to refresh the image itself without reloading the app, or is this impossible? I'm using the png library to generate the image.

    App code:

    from shiny import reactive, render, ui
    from shiny.express import input, ui

    import imagechanger

    with ui.card():
    ui.input_action_button("generate", "Generate")
    ui.input_slider("slider", "slider", value=1, min=1, max=100)
    @render.image
    def image():
    img = {"src": "image.png"}
    return img

    @reactive.effect
    @reactive.event(input.generate)
    def _():
    imagechanger.generate_png()
    pass


    Image generation code:

    import png
    import random

    width = 100
    height = 100

    img = []
    for y in range(height):
    row = []
    for x in range(width):
    row.append([0, 0, 0])
    img.append(row)

    def generate_png():
    for i in range(10):
    x = random.randint(1, width-1)
    y = random.randint(1, height-1)
    img[y][x] = [255, 255, 255]

    output = []
    for y in range(height):
    row = ()
    for x in img[y]:
    row += tuple(x)
    output.append(row)

    with open('image.png', 'wb') as f:
    w = png.Writer(width, height, greyscale=False)
    w.write(f, output)

    Continue reading...

Compartilhe esta Página