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

如何结合Pandas DataFrame实现PySimpleGUI列表框实时搜索更新?

解决PySimpleGUI实时筛选Pandas DataFrame内容到列表框的问题

错误分析

你的代码存在三个核心问题导致筛选功能失效:

  1. 未将Pandas Series转换为Python列表:names=formulation["PRODUCT"]得到的是Pandas Series对象,PySimpleGUI的Listbox组件需要普通字符串列表作为输入,直接传入Series会引发后续逻辑异常。
  2. 筛选逻辑完全错误:new_values=[formulation["PRODUCT"]==['-INPUT-']]这行代码是在判断Series是否等于固定字符串'-INPUT-',返回的是布尔值Series,并非匹配的产品名称列表。
  3. 列表推导式未适配数据类型:即使尝试了列表推导式,由于names是Series而非字符串列表,遍历过程会包含索引等无关数据,无法得到正确结果。

修正后的完整代码

import PySimpleGUI as sg 
import pandas as pd 

sg.theme('Default1')
pd.set_option('display.max_rows', None)

# 读取数据并将PRODUCT列转为字符串列表
formulation = pd.read_csv('FORMULATIONS.csv')
product_list = formulation["PRODUCT"].tolist()

# 左侧搜索栏布局
left_col = [
    [sg.Text('SEARCH')],
    [sg.Input(size=(20,1), enable_events=True, key='-INPUT-', do_not_clear=True)],
    [sg.Listbox(product_list, size=(50, len(product_list)), key='-LIST-', enable_events=True)]
]

# 右侧内容布局
right_col = [
    [sg.Text('Product : \n \n ITEM | RAW MATERIAL |')],
    [sg.Text(size=(40,1), key='-TOUT-')]
]

# 整体布局
layout = [
    [sg.Column(left_col, element_justification='c'), sg.VSeperator(), sg.Column(right_col)]
]

# 创建窗口
window = sg.Window('BF-2.1', layout, resizable=True)

# 事件循环
while True:
    event, values = window.read()
    if event in (sg.WIN_CLOSED, 'Exit'):
        break
    
    # 处理搜索输入
    search_input = values['-INPUT-'].strip()
    if search_input:
        # 方法1:列表推导式(小数据集适用)
        filtered_products = [p for p in product_list if search_input.lower() in p.lower()]
        # 方法2:Pandas str.contains(大数据集效率更高)
        # filtered_series = formulation[formulation["PRODUCT"].str.contains(search_input, case=False)]["PRODUCT"]
        # filtered_products = filtered_series.tolist()
        window['-LIST-'].update(filtered_products)
    else:
        # 输入为空时恢复完整列表
        window['-LIST-'].update(product_list)
    
    # 处理列表项选择事件
    if event == '-LIST-' and len(values['-LIST-']):
        sg.popup('Selected', values['-LIST-'])

window.close()

关键修正点说明

  1. 数据类型转换:将formulation["PRODUCT"]转为字符串列表product_list,确保Listbox和筛选逻辑能正确处理数据。
  2. 正确的筛选逻辑:使用列表推导式或Pandas的str.contains方法,实现输入内容的模糊匹配(通过lower()忽略大小写,提升用户体验)。
  3. 窗口更新优化:直接通过window['-LIST-'].update()方法传入筛选后的列表,替代原代码中错误的window.Element调用(PySimpleGUI推荐直接通过key访问组件)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 23:40:36