Upload code_editor.py (#1)
Browse files- Upload code_editor.py (aa136422594e1722ea458ab04de0c7658ea0b322)
- code_editor.py +54 -0
code_editor.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import tkinter as tk
|
| 2 |
+
from tkinter import scrolledtext
|
| 3 |
+
import sys
|
| 4 |
+
import io
|
| 5 |
+
|
| 6 |
+
class PythonCodeEditor:
|
| 7 |
+
def __init__(self, root):
|
| 8 |
+
self.root = root
|
| 9 |
+
self.root.title("Simple Python Code Editor")
|
| 10 |
+
self.root.geometry("600x400")
|
| 11 |
+
|
| 12 |
+
# Text area for writing Python code
|
| 13 |
+
self.text_area = scrolledtext.ScrolledText(self.root, width=70, height=15, wrap=tk.WORD)
|
| 14 |
+
self.text_area.grid(row=0, column=0, padx=10, pady=10)
|
| 15 |
+
|
| 16 |
+
# Run button to execute the code
|
| 17 |
+
self.run_button = tk.Button(self.root, text="Run", width=20, command=self.run_code)
|
| 18 |
+
self.run_button.grid(row=1, column=0, padx=10, pady=10)
|
| 19 |
+
|
| 20 |
+
# Output area to display the result
|
| 21 |
+
self.output_area = scrolledtext.ScrolledText(self.root, width=70, height=10, wrap=tk.WORD)
|
| 22 |
+
self.output_area.grid(row=2, column=0, padx=10, pady=10)
|
| 23 |
+
self.output_area.config(state=tk.DISABLED)
|
| 24 |
+
|
| 25 |
+
def run_code(self):
|
| 26 |
+
code = self.text_area.get("1.0", tk.END)
|
| 27 |
+
output = self.execute_code(code)
|
| 28 |
+
self.display_output(output)
|
| 29 |
+
|
| 30 |
+
def execute_code(self, code):
|
| 31 |
+
# Capture the output of the code execution
|
| 32 |
+
old_stdout = sys.stdout
|
| 33 |
+
redirected_output = sys.stdout = io.StringIO()
|
| 34 |
+
|
| 35 |
+
try:
|
| 36 |
+
exec(code)
|
| 37 |
+
except Exception as e:
|
| 38 |
+
sys.stdout = old_stdout
|
| 39 |
+
return f"Error: {str(e)}"
|
| 40 |
+
|
| 41 |
+
sys.stdout = old_stdout
|
| 42 |
+
return redirected_output.getvalue()
|
| 43 |
+
|
| 44 |
+
def display_output(self, output):
|
| 45 |
+
# Display the output in the output area
|
| 46 |
+
self.output_area.config(state=tk.NORMAL)
|
| 47 |
+
self.output_area.delete("1.0", tk.END)
|
| 48 |
+
self.output_area.insert(tk.END, output)
|
| 49 |
+
self.output_area.config(state=tk.DISABLED)
|
| 50 |
+
|
| 51 |
+
if __name__ == "__main__":
|
| 52 |
+
root = tk.Tk()
|
| 53 |
+
editor = PythonCodeEditor(root)
|
| 54 |
+
root.mainloop()
|