如何结合Pandas DataFrame实现PySimpleGUI列表框实时搜索更新?
解决PySimpleGUI实时筛选Pandas DataFrame内容到列表框的问题
错误分析
你的代码存在三个核心问题导致筛选功能失效:
- 未将Pandas Series转换为Python列表:
names=formulation["PRODUCT"]得到的是Pandas Series对象,PySimpleGUI的Listbox组件需要普通字符串列表作为输入,直接传入Series会引发后续逻辑异常。 - 筛选逻辑完全错误:
new_values=[formulation["PRODUCT"]==['-INPUT-']]这行代码是在判断Series是否等于固定字符串'-INPUT-',返回的是布尔值Series,并非匹配的产品名称列表。 - 列表推导式未适配数据类型:即使尝试了列表推导式,由于
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()
关键修正点说明
- 数据类型转换:将
formulation["PRODUCT"]转为字符串列表product_list,确保Listbox和筛选逻辑能正确处理数据。 - 正确的筛选逻辑:使用列表推导式或Pandas的
str.contains方法,实现输入内容的模糊匹配(通过lower()忽略大小写,提升用户体验)。 - 窗口更新优化:直接通过
window['-LIST-'].update()方法传入筛选后的列表,替代原代码中错误的window.Element调用(PySimpleGUI推荐直接通过key访问组件)。
内容的提问来源于stack exchange,提问作者mw00847
相关产品推荐
相关产品推荐

