PySimpleGUI加载弹窗异常:API调用时弹窗仅显黑框无加载文本
解决PySimpleGUI加载弹窗仅显示黑框的问题
你的问题出在创建弹窗后立即执行阻塞的API调用,导致窗口主线程被占用,来不及完成内容渲染,所以只显示黑框。可以通过以下两种方法解决:
方法一:强制刷新弹窗窗口
在弹窗创建完成后,调用window.refresh()方法强制完成UI渲染,再执行API调用:
def popup(message): sg.theme('DarkGrey14') layout = [[sg.Text(message)]] window = sg.Window('Message', layout, no_titlebar=True, keep_on_top=True, finalize=True) window.refresh() # 强制刷新窗口,确保文本内容渲染完成 return window def get_completion(prompt): popup_win = popup('Loading...') try: # 替换为实际的API调用代码 response = your_api_call_function(prompt) popup_win.close() return response.choices[0].message.content except Exception as e: sg.popup_error(f'Error: {str(e)}') popup_win.close() return None
方法二:添加短暂事件循环处理
如果refresh()效果不佳,可以在弹窗创建后处理一次窗口事件,给GUI预留渲染时间:
def popup(message): sg.theme('DarkGrey14') layout = [[sg.Text(message)]] window = sg.Window('Message', layout, no_titlebar=True, keep_on_top=True, finalize=True) # 处理一次超时事件,让GUI完成渲染 window.read(timeout=10) return window def get_completion(prompt): popup_win = popup('Loading...') try: response = your_api_call_function(prompt) popup_win.close() return response.choices[0].message.content except Exception as e: sg.popup_error(f'Error: {str(e)}') popup_win.close() return None
额外注意事项:
- 原代码中未定义
response变量,需确保API调用后正确赋值 - 避免使用裸
except,建议捕获具体异常类型,防止隐藏未知问题
内容的提问来源于stack exchange,提问作者Sahil
相关产品推荐
相关产品推荐

