PySimpleGUI程序通过PyCharm停止按钮关闭时出现KeyboardInterrupt报错求助
解决PySimpleGUI中PyCharm停止按钮触发KeyboardInterrupt报错的问题
当用PyCharm的停止按钮直接关闭PySimpleGUI窗口时,出现的KeyboardInterrupt报错,是因为停止按钮会向程序发送中断信号,而window.read()在阻塞等待用户事件时会捕获到这个信号,进而抛出Traceback。要消除这个报错,你可以通过以下两种方式处理:
方法1:捕获KeyboardInterrupt异常
直接对window.read()的调用做异常捕获,确保触发中断时能优雅关闭窗口,避免报错输出:
import PySimpleGUI as sg label = sg.Text('this is my first GUI') add_button = sg.Button('add') user_input = sg.InputText(tooltip='enter something here') window = sg.Window('Hello world', layout=[[label, user_input, add_button]]) try: window.read() except KeyboardInterrupt: pass finally: window.close()
方法2:使用标准事件循环模式
PySimpleGUI推荐用事件循环处理用户交互,这种模式既能规范代码结构,也能自然处理中断信号:
import PySimpleGUI as sg label = sg.Text('this is my first GUI') add_button = sg.Button('add') user_input = sg.InputText(tooltip='enter something here') window = sg.Window('Hello world', layout=[[label, user_input, add_button]]) try: while True: event, values = window.read() # 处理窗口关闭事件 if event == sg.WIN_CLOSED: break # 处理按钮点击事件(可根据需求扩展) if event == 'add': print(f'你输入了:{values[0]}') except KeyboardInterrupt: pass finally: window.close()
原理说明
- 捕获
KeyboardInterrupt异常后,程序会跳过Traceback输出,直接执行finally块的窗口关闭操作,保证资源被正确释放。 - 事件循环模式不仅能处理正常的窗口交互,还能在收到中断信号时通过异常捕获优雅退出,同时预留了扩展更多交互逻辑的空间。
内容的提问来源于stack exchange,提问作者Shubham SInha
相关产品推荐
相关产品推荐

