【发布时间】:2026-02-21 15:20:04
【问题描述】:
我正在编写一个非常简单的 Python Tkinter GUI 来驱动命令行 Python 脚本。
我的 GUI 将在 Windows 主机上运行,我希望它显示脚本的多行纯文本输出,该脚本作为包含 - 当然 - 换行符(\n 字符)的字符串返回到 GUI。
所以,我将一个 Text 小部件放入 GUI 中,当我的脚本(例如)返回一个以该子字符串开头的输出时:
RESULT STATUS: OK- Service is currently running\n\nDETAILS: ...
只要有 \n 换行符,显示的文本就会包含黑色竖线 (|)。
线条正确断开,但那些奇怪的条让我认为\n 换行符未正确解码,我不希望在显示的输出中出现这些条。
关于如何使 Tkinter 正确显示行尾的任何想法?提前致谢。
代码
这是我的 GUI 的工作流程:
- 我单击了一个按钮,该按钮调用 callMe() 回调函数
- callMe() 函数解析来自 Entry 小部件的参数,然后调用 python 命令行脚本
- 脚本返回上述字符串,回调使用它来更新 Text 小部件的文本
代码如下:
#init the GUI elements and the Text widget
from Tkinter import *
root = Tk()
top = Frame(root)
outputFrame = Frame(top)
outputFrame.pack(side='top', padx=20, pady=20)
outputTextArea = Text(outputFrame, yscrollcommand=scrollbar.set, width=150, height=40)
outputTextArea.pack(side='left', expand=YES, fill='both')
#callback executed when the button is clicked
def callMe()
#get parameters
# .....
#command line execution script execution
process = subprocess.Popen(command_line, stdout=subprocess.PIPE, shell=True)
#get script output
matr = process.stdout.readlines()
#from a list of strings to a single string
output = "".join(matr)
#write output into the Text widget
outputTextArea.insert(0.0, output)
【问题讨论】:
-
您说您将 Text 小部件放入 GUI 中,但您描述的行为听起来像是您正在使用 Entry 小部件。您确定您使用的是文本小部件吗?
标签: python user-interface character-encoding tkinter