【发布时间】:2015-02-04 07:57:06
【问题描述】:
我在堆栈溢出方面花了大约 6 个小时,重写了我的 python 代码并试图让它工作。它只是没有。不管我做什么。
目标: 让子进程的输出实时显示在 tkinter 文本框中。
问题: 我不知道如何使 Popen 实时工作。它似乎挂起,直到该过程完成。 (自行运行,过程完全按预期运行,所以只是这个东西有错误)
相关代码:
import os
import tkinter
import tkinter.ttk as tk
import subprocess
class Application (tk.Frame):
process = 0
def __init__ (self, master=None):
tk.Frame.__init__(self, master)
self.grid()
self.createWidgets()
def createWidgets (self):
self.quitButton = tk.Button(self, text='Quit', command=self.quit)
self.quitButton.grid()
self.console = tkinter.Text(self)
self.console.config(state=tkinter.DISABLED)
self.console.grid()
def startProcess (self):
dir = "C:/folder/"
self.process = subprocess.Popen([ "python", "-u", dir + "start.py" ], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE, cwd=dir)
self.updateLines()
def updateLines (self):
self.console.config(state=tkinter.NORMAL)
while True:
line = self.process.stdout.readline().decode().rstrip()
if line == '' and self.process.poll() != None:
break
else:
self.console.insert(tkinter.END, line + "\n")
self.console.config(state=tkinter.DISABLED)
self.after(1, self.updateLines)
app = Application()
app.startProcess()
app.mainloop()
另外,如果我的代码写得不好,请随意销毁我的代码。这是我的第一个 python 项目,我不希望自己擅长这门语言。
【问题讨论】:
标签: python python-3.x tkinter subprocess stdout