Reputation:
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
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