简体   繁体   English

有什么方法可以将代码的输出打印到 tkinter 文本框?

[英]Is there any way I can print the output of a code to a tkinter text box?

I am making a python IDE and I wanted to print the output of a file's code to the output text box.我正在制作一个 python IDE,我想将文件代码的输出打印到输出文本框中。 My current code doesnt work, it executes in the shell and the output is to the box is "None".我当前的代码不起作用,它在 shell 中执行,输出到框是“无”。 Code:代码:

from tkinter import *
input_box = Text()
output_box = Text()
def execute():
    code = input_box.get(1.0, END)
    out = exec(code)
    output.insert(1.0, str(out))

You can do this by redirecting the standard output as described in this answer .您可以按照此答案中的说明重定向标准输出来做到这一点。

def execute():
    code = input_box.get(1.0, "end")
    old_stdout = sys.stdout
    redirected_output = sys.stdout = StringIO()
    exec(code)
    sys.stdout = old_stdout
    output_box.delete(1.0, "end")
    output_box.insert(1.0, redirected_output.getvalue())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM