【问题标题】:Write to terminal in Tkinter GUI在 Tkinter GUI 中写入终端
【发布时间】:2016-07-19 21:36:42
【问题描述】:

我试图在我的 Tkinter GUI 中实时显示命令行中的更改,我设法创建了 GUI 并将终端集成到其中,但我无法将按钮与终端绑定,我的代码是:

import Tkinter
from Tkinter import *
import subprocess
import os
from os import system as cmd

WINDOW_SIZE = "600x400"
top = Tkinter.Tk()
top.geometry(WINDOW_SIZE)

def helloCallBack():
   print "Below is the output from the shell script in terminal"
   subprocess.call('perl /projects/tfs/users/$USER/scripts_coverage.pl', shell=True)
def BasicCovTests():
   print "Below is the output from the shell script in terminal"
   subprocess.call('perl /projects/tfs/users/$USER/basic_coverage_tests.pl', shell=True)
def FullCovTests():
   print "Below is the output from the shell script in terminal"
   subprocess.call('perl /projects/tfs/users/$USER/basic_coverage_tests.pl', shell=True)


Scripts_coverage  = Tkinter.Button(top, text ="Scripts Coverage", command = helloCallBack)
Scripts_coverage.pack()

Basic_coverage_tests  = Tkinter.Button(top, text ="Basic Coverage Tests", command = BasicCovTests)
Basic_coverage_tests.pack()

Full_coverage_tests  = Tkinter.Button(top, text ="Full Coverage Tests", command = FullCovTests)
Full_coverage_tests.pack()

termf = Frame(top, height=100, width=500)

termf.pack(fill=BOTH, expand=YES)
wid = termf.winfo_id()

os.system('xterm -into %d -geometry 100x20 -sb &' % wid)

def send_entry_to_terminal(*args):
    """*args needed since callback may be called from no arg (button)
   or one arg (entry)
   """
    cmd("%s" % (BasicCovTests))

top.mainloop()
#

我想赢我单击按钮以查看它在终端中打印命令

【问题讨论】:

    标签: python tkinter python-2.x


    【解决方案1】:

    好吧,您至少在正确的模块中。 subprocess 还包含用于查看您运行的命令输出的实用程序,以便您可以使用 perl 脚本的输出。

    如果您想在完成运行后简单地获取所有子进程的输出,请使用subrocess.check_output()。它应该绰绰有余。

    但是,如果子任务是一个长时间运行的程序或者您需要实时监控,您应该真正查看subprocess 模块中的Popen 类。您可以像这样创建和监控新流程:

    import subprocess
    
    p = subprocess.Popen("perl /projects/tfs/users/$USER/scripts_coverage.pl", stdout = subprocess.PIPE, stderr = subprocess.STDOUT, shell = True)   
    
    while True:
        line = p.stdout.readline()
        print line
        if not line: break
    

    您可以从那里将输出回显到终端或使用 Tkinter 小部件显示滚动程序输出。希望这会有所帮助。

    【讨论】:

    • 您好,感谢您的回复,您可能会错过了解我,我想在 python GUI 中打开的终端内查看 perl 脚本的输出
    • 是的,我想我明白你在这里想要做什么。好吧,如果你真的想在你的窗口中生成一个终端,为什么不使用subprocess.Popen() 而不是os.system()。至少这样你就可以在你的 python 程序和 xterm 进程之间建立一个链接。
    • 一旦你在 python 程序中引用了 Popen 对象,你就可以使用Popen.communicate() 与终端通信。我正在努力帮助您更多地思考您要在这里解决的问题。
    • 感谢您的帮助,我不是 python 专家,您能给我举个例子吗?如何使用 /: subprocess.Popen() 而不是 os.system() 以及如何使用 Popen.communicate() 在终端中显示输出。
    猜你喜欢
    • 2014-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-03
    • 2011-11-07
    • 1970-01-01
    • 2016-10-26
    • 1970-01-01
    相关资源
    最近更新 更多