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

如何在PySimpleGUI的Multiline元素中逐行追加显示多行内容

实现PySimpleGUI Multiline元素逐行追加内容不覆盖的方案

问题原因

现有代码中点击按钮后直接调用window['-STLINE-'].update(values['word']),update()方法默认是用新传入的内容替换Multiline元素的全部已有内容,所以才会出现新内容覆盖旧内容的情况。

修改方案

只需要调整Click here事件的处理逻辑即可,有两种常用实现方式:

方式1:手动拼接现有内容和新内容,再更新

每次新增内容前先读取Multiline当前的全部内容,拼接新内容后再通过update()回写,记得加换行符实现逐行排列:

if event == 'Click here':
    # 去除输入内容首尾空白,避免添加空行
    new_input = values['word'].strip()
    if new_input:
        # 已有内容 + 新内容 + 换行符
        updated_content = f"{values['-STLINE-']}{new_input}\n"
        window['-STLINE-'].update(updated_content)
        # 可选操作:输入完成后自动清空输入框,方便下一次输入
        window['word'].update('')

方式2:使用Multiline自带的print()方法(更简便)

PySimpleGUI的Multiline元素内置了print()方法,默认就是把内容追加到现有内容末尾,且自动添加换行符,不需要手动拼接:

if event == 'Click here':
    new_input = values['word'].strip()
    if new_input:
        window['-STLINE-'].print(new_input)
        window['word'].update('')

修改后完整可运行代码

import PySimpleGUI as sg

sz = (7,1)

column1 = [ [sg.ReadButton('UPDATE\nTEXT', size=sz)],
            [sg.ReadButton('LOAD-\nTEXT', size=sz)],
            [sg.ReadButton('SAVE-VOC', size=sz)],
            [sg.ReadButton('CLEAR\nTEXT', size=sz)]
            ]

column2 = [[sg.ReadButton('Click here')]]

col_layout = [
                [sg.InputText(focus=True, key='word')],
                [sg.Column(column2)]
             ]

layout = [
            [sg.Text("Study Text Box")],
            [sg.Multiline(size=(50,10), font='Tahoma 13', key='-STLINE-', autoscroll=True), sg.Column(column1), sg.VerticalSeparator(pad=None), sg.Column(col_layout)]
         ]
        

window = sg.Window("TbLLT Program", layout, resizable=True, finalize=True)

while True:
    event, values=window.read()
    if event == sg.WIN_CLOSED or event == 'Exit':
        break
    if event == 'SAVE-VOC':
        with open('someText(saved).txt', 'w+', encoding='utf-8') as file:
            file.write(values['-STLINE-'])
    if event == 'Click here':
        new_input = values['word'].strip()
        if new_input:
            window['-STLINE-'].print(new_input)
            window['word'].update('')
window.close()

额外优化说明:给保存文件的open方法加了encoding='utf-8'参数,避免保存中文等非ASCII字符时出现乱码

窗口效果参考

带输入框的Multiline窗口

内容的提问来源于stack exchange,提问作者G. Trialonis

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 05:36:02