pythonttkinter条目小部件显示条字符而不是换行符

2024-09-24 00:32:57 发布

您现在位置:Python中文网/ 问答频道 /正文



我正在编写一个非常简单的Python Tkinter GUI来驱动命令行Python脚本。
我的GUI将在Windows主机上运行,我希望它显示脚本的多行纯文本输出,它作为一个字符串返回给GUI,其中当然包含换行符(\n字符)。在

因此,我将一个文本小部件放入GUI中,当我的脚本(在示例中)返回以以下子字符串开头的输出时:

RESULT STATUS: OK- Service is currently running\n\nDETAILS: ...

当有\n换行符时,显示的文本包含黑色竖线(|)。

行被正确地打断了,但是那些奇怪的条使我认为\n换行符没有被正确解码,我不希望在显示的输出中出现这些条。

有什么办法让Tkinter正确地显示行尾吗?提前谢谢。在

代码

这是我的GUI的工作流程:

  1. 我单击一个按钮,它调用callMe()回调函数
  2. 函数的作用是:解析来自条目小部件的参数,然后调用python命令行脚本
  3. 该脚本返回上述字符串,回调将使用该字符串更新文本小部件的文本

代码如下:

#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)

Tags: the字符串代码text命令行文本脚本output
3条回答

如果没有看到您的代码,就不可能确定问题出在哪里。您说您使用文本小部件,但行为似乎与使用条目小部件一致。你还看到带有以下代码的竖线吗?在

import Tkinter as tk

OUTPUT = "RESULT STATUS: OK- Service is currently running\n\nDETAILS: ... "

root = tk.Tk()
text = tk.Text(root, height=4, width=80)
text.pack(fill="both", expand="true")
text.insert("end", OUTPUT)

root.mainloop()

可能是每个'\n'字符前面有'\r'个字符的问题(您说过您在Windows上)。在

在更新小部件之前,请先尝试:

text_output= text_output.replace('\r', '')

(text_output包含脚本的输出,其内容将插入小部件中)

如果你能给我们更多的信息,我们可以帮助你更多。在

何时使用条目小部件(来自http://effbot.org/tkinterbook/entry.htm

entry小部件用于输入文本字符串。这个小部件允许用户以单一字体输入一行文本。在

要输入多行文本,请使用文本小部件。在

相关问题 更多 >