PySimpleGUI代码运行正常但调用sg.WIN_CLOSED()报TypeError求解
问题说明
编写PySimpleGUI代码实现用户选中选项后自动关闭窗口的功能,代码运行效果符合预期,但窗口关闭时返回如下错误:
sg.WIN_CLOSED() TypeError: 'NoneType' object is not callable
已知这类错误一般是混淆了变量与函数的调用方式,但不清楚功能正常仍触发报错的原因。
原代码如下:
import PySimpleGUI as sg options = ['Go on date', 'Stay in'] layout = [ [sg.Text("Choose one->"), sg.Listbox(options, select_mode=sg.LISTBOX_SELECT_MODE_SINGLE, size=(50, len(options)))], [sg.Button("Date"), sg.Button("Stay in")] ] # Create the Window window = sg.Window("Question", layout) # Event Loop to process "events" and get the "values" of the input while True: event, values = window.read() print(f"event={event}") if event is None or event == "Date" or event == "Stay in": # if user closes window or clicks cancel break if event == "Date": print("Let's go on a date!") # close the window sg.WIN_CLOSED() else: print('Lets stay in') sg.popup(f"You selected to stay in") # close the window sg.WIN_CLOSED()
报错原因
sg.WIN_CLOSED 不是可调用的函数,是PySimpleGUI内置的事件常量,值等价于None,作用是和window.read()返回的事件做比对,判断用户是否点击了窗口右上角的原生关闭按钮。
你在代码里给sg.WIN_CLOSED加了括号尝试调用,本质是在执行None(),自然会抛出"NoneType对象不可调用"的类型错误。
你觉得功能正常是错觉:事件循环触发break跳出后,窗口已经失去了事件循环的保活,会被自动回收销毁,和你写的两行sg.WIN_CLOSED()没有任何关系——这两行代码除了抛错之外没有执行任何有效逻辑,所以才会出现"功能正常但报错"的现象。
修正方案
- 删除所有错误的
sg.WIN_CLOSED()调用,跳出事件循环后统一调用窗口实例的close()方法完成关窗和资源释放 - 补充右上角关闭窗口的分支判断,避免用户点关闭按钮时错误走到"Stay in"的逻辑分支
修正后的参考代码:
import PySimpleGUI as sg options = ['Go on date', 'Stay in'] layout = [ [sg.Text("Choose one->"), sg.Listbox(options, select_mode=sg.LISTBOX_SELECT_MODE_SINGLE, size=(50, len(options)))], [sg.Button("Date"), sg.Button("Stay in")] ] window = sg.Window("Question", layout) while True: event, values = window.read() print(f"event={event}") # 点关闭按钮、点两个功能按钮都跳出循环 if event in (sg.WIN_CLOSED, "Date", "Stay in"): break if event == "Date": print("Let's go on a date!") elif event == "Stay in": print('Lets stay in') sg.popup(f"You selected to stay in") # 统一关窗释放资源 window.close()
内容的提问来源于stack exchange,提问作者Teckla
相关产品推荐
相关产品推荐

