user17871322
user17871322

Reputation:

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. My current code doesnt work, it executes in the shell and the output is to the box is "None". 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))

Upvotes: 0

Views: 678

Answers (1)

Henry
Henry

Reputation: 3942

You can do this by redirecting the standard output as described in this answer.

import sys
from io import StringIO
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())

Upvotes: 2

Related Questions