You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用timeout参数与window.update时,PySimpleGui窗口关闭报错问题

PySimpleGui带timeout参数时关闭窗口报错的解决方法

问题根源在于代码执行顺序错误:原逻辑中每次调用window.read(timeout=100)后,会先执行图片更新操作,再判断窗口是否关闭。当点击关闭按钮触发sg.WIN_CLOSED事件时,窗口已进入关闭流程,此时再调用window['-IMAGE-'].update()会因组件已失效而报错。

只需调整代码顺序,先判断窗口关闭事件,再执行更新操作即可解决问题,同时补充处理Exit按钮的事件,确保所有关闭入口都能正常工作:

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)
    
    # 优先处理窗口关闭相关事件,避免操作已失效的组件
    if event == sg.WIN_CLOSED or event == 'Exit':
        break
    
    image_data = create_image().read()
    window['-IMAGE-'].update(data=image_data)

window.close()

内容的提问来源于stack exchange,提问作者Leonick

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 13:45:30