如何从另一个 Tkinter 脚本中调用的 gui 中的脚本打印输出? [英] How to print output from a script in gui called in another Tkinter script?

查看:51
本文介绍了如何从另一个 Tkinter 脚本中调用的 gui 中的脚本打印输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用在网上找到的几种不同的类似解决方案,但似乎没有一个完全符合我的目标.

I have tried using several different similar solutions that I have found online, but none seem to quite do what I am aiming for.

我想在我的 tkinter gui 中调用外部脚本 (helloworld.py).我希望这个名为的脚本 (helloworld.py) 在 gui 中按下按钮时执行其中包含的所有函数,并将结果输出打印到 gui 中,而不是控制台.我找到了一些将输出打印到控制台的解决方案,但我无法将其显示在 gui 中.当我尝试从调用的外部脚本获取输出时,我发现打印到 gui 的任何解决方案都不起作用.

I want to call an external script (helloworld.py) into my tkinter gui. I want this called script (helloworld.py) to execute all the functions that are contained in it upon a button press in the gui and print the resulting outputs into the gui, not the console. I have found some solutions which will print the output to the console, but I am unable to get it to display in the gui. Any solutions that I have found that print to the gui do not work when I try to get the output to come from a called external script.

感谢您的帮助.我绝对是一个新手,所以我很抱歉这可能是一个基本问题,并且无法在此处提出的类似问题上为自己连接点.以下是我目前正在使用的代码版本之一.预先感谢您的帮助!

I appreciate any help. I am definitely a novice, so I apologize for what is probably a basic question and the inability to connect the dots for myself on similar questions asked on here. Below is one of the versions of code that I am currently working with. Thank you in advance for your help!

import Tkinter
import sys
import subprocess
sys.path.append('/users/cmbp')

def callback():
    import os
    print subprocess.call('python /users/cmbp/p4e/helloworld.py', 
shell=True)
    lbl = Tkinter.Label(master)
    lbl.pack()

master = Tkinter.Tk()
master.geometry('200x90')
master.title('Input Test')

Btn1 = Tkinter.Button(master, text="Input", command=callback)
Btn1.pack()

master.mainloop()

编辑

我也开始尝试将被调用的脚本作为模块导入,取得了一些成功.问题是我只能从被调用的脚本中打印出一个函数,即使我想尝试和调用多个函数(我只希望整个被调用的脚本打印出其函数的所有结果).

I also started having some success with trying to import the called script as a module. The problem with this is I can only get one function to print out from the called script even though there are multiple functions that I want to try and call (I just want the entire called script to print out all the results of its functions).

这是我想调用 helloworld.py 的脚本示例:

Here is an example of a script that I want to call helloworld.py:

def cooz():
    return ('hello worldz!')

def tooz():
    return ("here is another line")

def main():
    return cooz()
    return tooz()

这是一个尝试导入 helloworld.py 的 tkinter gui 脚本示例:

And here is an example of the tkinter gui script that is trying to import helloworld.py:

import Tkinter as tk
import helloworld

def printSomething():
    y = helloworld.main()
    label = tk.Label(root, text= str(y))
    label.pack()


root = tk.Tk()
root.geometry('500x200')
root.title('Input Test')

button = tk.Button(root, text="Print Me", command=printSomething)
button.pack()

root.mainloop()

这只会打印第一个函数('hello worldz!').关于为什么它只会返回一行而不是整个 helloworld.py 脚本的任何想法?

This results in only the first function printing ('hello worldz!'). Any thoughts on why it only will return one line and not the entire helloworld.py script?

推荐答案

您可以使用 subprocess.check_output() 获取输出并分配给 Label

You can use subprocess.check_output() to get output and assign to Label

您还可以import 脚本并从脚本执行功能.

You can also import script and execute function from script.

import test
test.function()

但首先您必须使用带有 write() 的类重定向 sys.stdout,然后它将捕获所有打印的文本.

But first you will have to redirect sys.stdout using class with write() and then it will catch all printed text.

您可以将 sys.stdout 重定向到变量(请参阅 StdoutRedirector),然后您可以对其进行编辑(即删除 \n 在end) 或者您可以直接重定向到 Label(请参阅 StdoutRedirectorLabel)

You can redirect sys.stdout to variable (see StdoutRedirector) and then you can edit it (ie. strip \n at the end) or you can redirect directly to Label (see StdoutRedirectorLabel)

import Tkinter as tk

# -----

import subprocess

def callback1():
    cmd = 'python test.py'

    # it will execute script which runs only `function1`
    output = subprocess.check_output(cmd, shell=True)

    lbl['text'] = output.strip()

# -----

class StdoutRedirector(object):

    def __init__(self):
        # clear before get all values
        self.result = ''

    def write(self, text):
        # have to use += because one `print()` executes `sys.stdout` many times
        self.result += text

def callback2():

    import test

    # keep original `sys.stdout
    old_stdout = sys.stdout

    # redirect to class which has `self.result`
    sys.stdout = StdoutRedirector()

    # it will execute only `function2`
    test.function2()

    # assign result to label (after removing ending "\n")
    lbl['text'] = sys.stdout.result.strip()

    # set back original `sys.stdout
    sys.stdout = old_stdout

# -----

import sys

class StdoutRedirectorLabel(object):

    def __init__(self, widget):
        self.widget = widget
        # clear at start because it will use +=
        self.widget['text'] = ''

    def write(self, text):
        # have to use += because one `print()` executes `sys.stdout` many times
        self.widget['text'] += text

def callback3():

    import test

    # keep original `sys.stdout
    old_stdout = sys.stdout

    # redirect to class which will add text to `lbl`
    sys.stdout = StdoutRedirectorLabel(lbl)

    # it will execute only `function3` and assign result to Label (with ending "\n")
    test.function3()

    # set back original `sys.stdout
    sys.stdout = old_stdout

# --- main ---

master = tk.Tk()
master.geometry('200x200')

lbl = tk.Label(master, text='')
lbl.pack()

btn1 = tk.Button(master, text="subprocess", command=callback1)
btn1.pack()

btn2 = tk.Button(master, text="StdoutRedirector", command=callback2)
btn2.pack()

btn3 = tk.Button(master, text="StdoutRedirectorLabel", command=callback3)
btn3.pack()

master.mainloop()

test.py

def function1():
    print('function 1')

def function2():
    print('function 2')

def function3():
    print('function 3')

if __name__ == '__main__':
    function1() 

这篇关于如何从另一个 Tkinter 脚本中调用的 gui 中的脚本打印输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆