File size: 1,891 Bytes
4fe5a1a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import tkinter as tk
from tkinter import scrolledtext
import sys
import io

class PythonCodeEditor:
    def __init__(self, root):
        self.root = root
        self.root.title("Simple Python Code Editor")
        self.root.geometry("600x400")

        # Text area for writing Python code
        self.text_area = scrolledtext.ScrolledText(self.root, width=70, height=15, wrap=tk.WORD)
        self.text_area.grid(row=0, column=0, padx=10, pady=10)

        # Run button to execute the code
        self.run_button = tk.Button(self.root, text="Run", width=20, command=self.run_code)
        self.run_button.grid(row=1, column=0, padx=10, pady=10)

        # Output area to display the result
        self.output_area = scrolledtext.ScrolledText(self.root, width=70, height=10, wrap=tk.WORD)
        self.output_area.grid(row=2, column=0, padx=10, pady=10)
        self.output_area.config(state=tk.DISABLED)

    def run_code(self):
        code = self.text_area.get("1.0", tk.END)
        output = self.execute_code(code)
        self.display_output(output)

    def execute_code(self, code):
        # Capture the output of the code execution
        old_stdout = sys.stdout
        redirected_output = sys.stdout = io.StringIO()

        try:
            exec(code)
        except Exception as e:
            sys.stdout = old_stdout
            return f"Error: {str(e)}"

        sys.stdout = old_stdout
        return redirected_output.getvalue()

    def display_output(self, output):
        # Display the output in the output area
        self.output_area.config(state=tk.NORMAL)
        self.output_area.delete("1.0", tk.END)
        self.output_area.insert(tk.END, output)
        self.output_area.config(state=tk.DISABLED)

if __name__ == "__main__":
    root = tk.Tk()
    editor = PythonCodeEditor(root)
    root.mainloop()