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

使用PySimpleGUI操作第二个窗口时触发KeyError的问题排查

问题:PySimpleGUI多窗口操作触发KeyError("IN")

用户实现功能:通过搜索框搜索姓名,选择目标姓名后弹出第二个窗口录入信息。但操作第二个窗口时,会触发values["IN"]的KeyError,未调用第二个窗口时程序运行正常。

报错信息

Traceback (most recent call last):
  File "C:\Users\ps2ee\Downloads\Testmulti.py", line 59, in <module>
    main()
  File "C:\Users\ps2ee\Downloads\Testmulti.py", line 36, in main
    if values['IN'] != '':
KeyError: 'IN'

问题原因

当操作第二个窗口(window2)时,sg.read_all_windows()返回的window指向window2,此时values字典仅包含当前窗口(window2)的元素键值对。而window2中不存在IN这个控件key,直接访问values['IN']就会抛出KeyError。

原代码中每次循环都会无条件执行搜索框相关逻辑,没有判断当前操作的是哪个窗口,导致操作window2时必然报错。

解决方案

添加判断,只有当当前操作的是window1时,才执行搜索框的过滤逻辑。

修正后的完整代码

import PySimpleGUI as sg

pt_list = ["Test 1", "Test 2", "Test 3"]

def make_window1():
    layout = [
        [sg.Button("Add New Patient", key = "ADD"), sg.Button("Remove Patient", key = "RMV")],
        [sg.Input("Search patient name", key = "IN", enable_events = True), sg.Button("Search", key = "SEARCH")],
        [sg.Listbox(pt_list, expand_x = True, expand_y = True, key = "LIST", enable_events = True)]
        ]

    return sg.Window("WINDOW1", layout, finalize = True)

def make_window2():
    layout = [
        [sg.Text("A second window has appeared.")],
        [sg.Button("Close 2nd window")],
        ]

    return sg.Window("WINDOW2", layout, finalize = True)

def main():
    window2 = None
    window1 = make_window1()

    while True:
        window, event, values = sg.read_all_windows()
        if event == sg.WIN_CLOSED and window == window1 or event == "Quit":
            break

        # 仅当操作的是window1时,执行搜索框过滤逻辑
        if window == window1:
            # 患者选择列表逻辑
            if values['IN'] != '':                          
                search = values['IN']
                # 过滤列表
                new_values = [x for x in pt_list if search in x]
                # 更新列表框显示
                window['LIST'].update(new_values)     
            else:
                # 显示原始未过滤列表
                window['LIST'].update(pt_list)
            # 选择列表项后弹出第二个窗口
            if event == 'LIST' and len(values['LIST']):
                window2 = make_window2()
                window1.hide()

        # 处理第二个窗口的关闭事件
        if window == window2 and (event in (sg.WIN_CLOSED, 'Close 2nd window')):
            window2.close()
            window2 = None
            window1.un_hide()
    window1.close()

# 运行程序
if __name__ == '__main__':
    main()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 14:18:17