Python PySimpleGui gives error when closing window with "X", when using "=timeout" and "window.update" in loop

693 Views Asked by At

When I use the =timeout argument, I cannot seem to make it work, that if I close the window with the X button, that I don't get a error.

Here is a code snippet from the web, where it was suggested to use

if event == sg.WIN_CLOSED:

But as soon as I use the =timeout argument, AND window.update it fails.

from io import BytesIO
from PIL import Image
import PySimpleGUI as sg
import random

def create_image():
    file = BytesIO()
    image = Image.new('RGB', size=(300, 380), color=(random.randint(0,250), 50, 50))
    image.save(file, 'png')
    file.name = 'image.png'
    file.seek(0)
    return file

image_data = create_image().read()

print(sg.version, sg)

layout = [[sg.Image(key='-IMAGE-')],
          [sg.Button('Refresh', key='-REFRESH-'), sg.Exit()]]

window = sg.Window('Image Update Issue', layout, finalize=True)
window['-IMAGE-'].update(data=image_data)

while True:
    event, values = window.read(timeout=100)
    image_data = create_image().read()
    window['-IMAGE-'].update(data=image_data)

    if event == sg.WIN_CLOSED:
        break

window.close()

1

There are 1 best solutions below

3
Leonick On

I just found the answer while making coffee. The solution is to put the image update AFTER the event check! Because after the timeout timer runs out, the first thing the code does, is to update the image, instead it should check if the window was closed...solved.

Should I delete my question or let it stay for others?

while True:
    event, values = window.read(timeout=100)

    if event == sg.WIN_CLOSED:
        break
    image_data = create_image().read()
    window['-IMAGE-'].update(data=image_data)

window.close()