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

PySimpleGUI写入Listbox时元素逐字符分行显示问题

问题根因

PySimpleGUI的Listbox.update()方法接收的待展示内容参数必须是列表/元组类型的可迭代集合,每个集合元素对应列表的单独一行。
你当前代码直接传入了字符串类型的filename,Python中字符串本身是按单个字符迭代的序列,控件会自动遍历传入的可迭代对象,把每个迭代到的元素(也就是单个字符)渲染为单独一行,就出现了字符拆分显示的异常。
另外原代码还存在3个逻辑问题:

  • 多余的for x in values遍历无实际作用,按钮事件判断不需要遍历所有返回值
  • 每次调用update直接传入新值会覆盖列表原有内容,无法实现累加添加多个路径的效果
  • 未做输入空值校验,空输入也会被写入列表
修复方案
  1. 单独维护一个列表变量存储所有已添加的文件路径
  2. 点击Add按钮时,先判断输入框内容非空,再将新路径追加到存储列表中
  3. 调用Listbox的update方法时,传入整个存储列表作为参数
  4. 移除多余的values遍历逻辑
修复后可运行代码
import PySimpleGUI as sg

# 存储所有已添加的文件路径
file_list = []

file_list_column = [
    [
        sg.Text("File Path"),
        sg.In(size=(25, 1), enable_events=True, key="-File Path-"),
        sg.Button(size=(10, 1), enable_events=True, key="-AddButton-", button_text="Add"),
    ],
    [
        sg.Listbox(
            values=file_list, enable_events=True, size=(40, 20), key="-File List-"
        )
    ],
    [
        sg.Button(size=(15, 1), enable_events=True, key="-create-", button_text="Create")
    ],
]

layout = [
    [
        sg.Column(file_list_column),
    ]
]

window = sg.Window("Startup Script", layout)

while True:
    event, values = window.read()
    if event == "Exit" or event == sg.WIN_CLOSED:
        break
    if event == "-AddButton-":
        filename = values["-File Path-"].strip()
        # 空输入不添加
        if filename:
            file_list.append(filename)
            # 传入完整列表更新控件
            window["-File List-"].update(file_list)
            # 可选:添加后清空输入框
            window["-File Path-"].update("")
window.close()
异常复现效果

Listbox单字符占一行异常效果


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 21:54:32