我正在编写一个非常简单的Python Tkinter GUI来驱动命令行python脚本
我的GUI将在Windows主机上运行,我希望它显示脚本的多行纯文本输出,该输出作为字符串返回到GUI,当然包含换行符(\n
个字符)
因此,我将一个Text小部件放入GUI中,当我的脚本(例如)返回一个以该子字符串开头的输出时:
RESULT STATUS: OK- Service is currently running\n\nDETAILS: ...
只要有|
换行符,显示的文本就会包含黑色竖条(\n
)。
线被正确打破但是那些奇怪的条让我觉得\n
换行符没有被正确解码,我不希望显示输出中的条。
有关如何使Tkinter正确显示行结尾的任何想法?提前谢谢。
这是我的GUI的工作流程:
以下是代码:
#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)
答案 0 :(得分:3)
在每个'\ n'字符之前可能是'\ r'字符的问题(你说你在Windows上)。
在更新小部件之前,请先尝试:
text_output= text_output.replace('\r', '')
(text_output包含脚本的输出,其内容将插入到小部件中)
如果您向我们提供更多信息,我们可以为您提供更多帮助。
答案 1 :(得分:0)
何时使用Entry Widget(来自http://effbot.org/tkinterbook/entry.htm)
条目小部件用于输入文本字符串。此小部件允许用户以单一字体输入一行文本。
要输入多行文字,请使用文本小部件。
答案 2 :(得分:0)
如果没有看到您的代码,就无法确定问题是什么。您说您使用文本小部件,但行为似乎与使用条目小部件一致。您是否仍然看到带有以下代码的竖条?
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()
答案 3 :(得分:0)
由于ΤΖΩΤΖΙΟΥ,我解决了这个问题..这是/r
个字符的问题。我想当我调用subprocess.Popen运行我的命令行脚本时,Windows命令提示符已打开,脚本已执行,标识输出流由带有/r/n
行结尾的提示符返回,而不仅仅是/n
。
无论如何,我会一直发布代码和GUI工作流程......
这是我的GUI的工作流程:
以下是代码:
#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) # <<< now it is: output = "".join(matr).replace('\r', '')
#write output into the Text widget
outputTextArea.insert(0.0, output)
非常感谢你们所有人,伙计们!