-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple python ide.py
More file actions
824 lines (709 loc) · 32.5 KB
/
Copy pathsimple python ide.py
File metadata and controls
824 lines (709 loc) · 32.5 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
"""
PyIDE — A Python IDE built entirely in Python using tkinter.
Run with: python3 python_ide.py
Requires: Python 3.6+ (tkinter is included in standard Python installs)
"""
import tkinter as tk
from tkinter import ttk, filedialog, messagebox, font
import subprocess
import threading
import os
import sys
import re
import json
import tempfile
from pathlib import Path
# ─────────────────────────── Syntax Highlighter ────────────────────────────
KEYWORDS = {
"keyword": r'\b(False|None|True|and|as|assert|async|await|break|class|continue|'
r'def|del|elif|else|except|finally|for|from|global|if|import|in|is|'
r'lambda|nonlocal|not|or|pass|raise|return|try|while|with|yield)\b',
"builtin": r'\b(print|len|range|int|str|float|list|dict|tuple|set|bool|type|'
r'input|open|enumerate|zip|map|filter|sorted|reversed|sum|min|max|'
r'abs|round|repr|super|object|isinstance|issubclass|hasattr|getattr|'
r'setattr|delattr|dir|vars|id|hex|oct|bin|chr|ord|format|any|all|'
r'next|iter|hash|callable)\b',
"string": r'("""[\s\S]*?"""|\'\'\'[\s\S]*?\'\'\'|"[^"\n]*"|\'[^\'\n]*\')',
"comment": r'(#[^\n]*)',
"number": r'\b(\d+\.?\d*([eE][+-]?\d+)?|0x[0-9a-fA-F]+|0b[01]+|0o[0-7]+)\b',
"decorator": r'(@\w+)',
"classname": r'\b(class\s+)([A-Z]\w*)',
"funcname": r'\b(def\s+)(\w+)',
}
COLORS = {
"keyword": "#c678dd",
"builtin": "#61afef",
"string": "#98c379",
"comment": "#5c6370",
"number": "#d19a66",
"decorator": "#e5c07b",
"classname": "#e5c07b",
"funcname": "#61afef",
"self": "#e06c75",
}
class SyntaxHighlighter:
def __init__(self, text_widget):
self.widget = text_widget
for tag, color in COLORS.items():
self.widget.tag_configure(tag, foreground=color)
self.widget.tag_configure("self_kw", foreground=COLORS["self"])
def highlight(self, event=None):
content = self.widget.get("1.0", "end-1c")
for tag in list(COLORS.keys()) + ["self_kw"]:
self.widget.tag_remove(tag, "1.0", "end")
for tag, pattern in KEYWORDS.items():
for m in re.finditer(pattern, content):
if tag in ("classname", "funcname"):
start = self._offset_to_index(content, m.start(2))
end = self._offset_to_index(content, m.end(2))
else:
start = self._offset_to_index(content, m.start())
end = self._offset_to_index(content, m.end())
self.widget.tag_add(tag, start, end)
for m in re.finditer(r'\bself\b', content):
start = self._offset_to_index(content, m.start())
end = self._offset_to_index(content, m.end())
self.widget.tag_add("self_kw", start, end)
def _offset_to_index(self, content, offset):
line = content[:offset].count('\n') + 1
col = offset - content[:offset].rfind('\n') - 1
return f"{line}.{col}"
# ─────────────────────────── Line Number Bar ───────────────────────────────
class LineNumbers(tk.Canvas):
def __init__(self, parent, text_widget, **kw):
super().__init__(parent, width=50, **kw)
self.text_widget = text_widget
self.configure(bg="#21252b", highlightthickness=0)
self.text_widget.bind("<KeyRelease>", self.redraw)
self.text_widget.bind("<MouseWheel>", self.redraw)
self.text_widget.bind("<Button-4>", self.redraw)
self.text_widget.bind("<Button-5>", self.redraw)
self.text_widget.bind("<<Change>>", self.redraw)
self.text_widget.bind("<Configure>", self.redraw)
def redraw(self, event=None):
self.delete("all")
i = self.text_widget.index("@0,0")
while True:
dline = self.text_widget.dlineinfo(i)
if dline is None:
break
y = dline[1]
linenum = int(str(i).split(".")[0])
self.create_text(46, y + 1, anchor="ne", text=str(linenum),
fill="#636d83", font=("Consolas", 11))
i = self.text_widget.index(f"{i}+1line")
if i == self.text_widget.index(f"{i}+1line"):
break
# ─────────────────────────── Auto-complete ────────────────────────────────
AUTOCOMPLETE_WORDS = [
"False", "None", "True", "and", "as", "assert", "async", "await",
"break", "class", "continue", "def", "del", "elif", "else", "except",
"finally", "for", "from", "global", "if", "import", "in", "is",
"lambda", "nonlocal", "not", "or", "pass", "raise", "return", "try",
"while", "with", "yield", "print", "len", "range", "int", "str",
"float", "list", "dict", "tuple", "set", "type", "input", "open",
"enumerate", "zip", "map", "filter", "sorted", "reversed", "sum",
"min", "max", "abs", "round", "super", "self", "isinstance",
"__init__", "__str__", "__repr__", "__len__", "__main__",
]
class AutoComplete:
def __init__(self, text_widget):
self.widget = text_widget
self.popup = None
self.listbox = None
self.widget.bind("<KeyRelease>", self.on_key)
self.widget.bind("<Escape>", self.hide)
self.widget.bind("<FocusOut>", self.hide)
def get_current_word(self):
idx = self.widget.index("insert")
line_start = f"{idx.split('.')[0]}.0"
line_text = self.widget.get(line_start, idx)
m = re.search(r'\w+$', line_text)
return m.group() if m else ""
def on_key(self, event):
if event.keysym in ("Return", "Tab", "Up", "Down", "Escape"):
return
word = self.get_current_word()
if len(word) < 2:
self.hide()
return
matches = [w for w in AUTOCOMPLETE_WORDS if w.startswith(word) and w != word]
if matches:
self.show(matches)
else:
self.hide()
def show(self, matches):
self.hide()
x, y, _, h = self.widget.bbox("insert")
rx = self.widget.winfo_rootx() + x
ry = self.widget.winfo_rooty() + y + h
self.popup = tk.Toplevel(self.widget)
self.popup.wm_overrideredirect(True)
self.popup.geometry(f"+{rx}+{ry}")
self.listbox = tk.Listbox(self.popup, bg="#2c313c", fg="#abb2bf",
selectbackground="#528bff",
font=("Consolas", 11), relief="flat",
highlightthickness=1,
highlightbackground="#3e4452",
height=min(6, len(matches)))
self.listbox.pack()
for m in matches:
self.listbox.insert("end", m)
self.listbox.selection_set(0)
self.listbox.bind("<Return>", self.complete)
self.listbox.bind("<Tab>", self.complete)
self.listbox.bind("<Double-Button-1>", self.complete)
self.widget.bind("<Tab>", self.complete)
self.widget.bind("<Down>", lambda e: self._nav(1))
self.widget.bind("<Up>", lambda e: self._nav(-1))
def _nav(self, direction):
if not self.listbox:
return
cur = self.listbox.curselection()
idx = (cur[0] + direction) % self.listbox.size() if cur else 0
self.listbox.selection_clear(0, "end")
self.listbox.selection_set(idx)
self.listbox.see(idx)
def complete(self, event=None):
if not self.listbox:
return "break"
sel = self.listbox.curselection()
if sel:
word = self.get_current_word()
chosen = self.listbox.get(sel[0])
idx = self.widget.index("insert")
line, col = idx.split(".")
start = f"{line}.{int(col) - len(word)}"
self.widget.delete(start, idx)
self.widget.insert(start, chosen)
self.hide()
return "break"
def hide(self, event=None):
self.widget.unbind("<Tab>")
self.widget.unbind("<Down>")
self.widget.unbind("<Up>")
self.widget.bind("<Tab>", lambda e: self._insert_tab())
if self.popup:
self.popup.destroy()
self.popup = None
self.listbox = None
def _insert_tab(self):
self.widget.insert("insert", " ")
return "break"
# ─────────────────────────── Editor Tab ───────────────────────────────────
class EditorTab:
def __init__(self, notebook, filename=None):
self.notebook = notebook
self.filename = filename
self.modified = False
self.frame = ttk.Frame(notebook)
notebook.add(self.frame, text=self._tab_label())
# Line numbers + editor side by side
editor_row = tk.Frame(self.frame, bg="#282c34")
editor_row.pack(fill="both", expand=True)
self.text = tk.Text(
editor_row,
bg="#282c34", fg="#abb2bf",
insertbackground="#528bff",
selectbackground="#3e4452",
font=("Consolas", 12),
relief="flat", bd=0,
wrap="none",
undo=True,
padx=8, pady=6,
tabs=("1c",),
)
self.line_bar = LineNumbers(editor_row, self.text, bd=0)
self.line_bar.pack(side="left", fill="y")
scroll_y = ttk.Scrollbar(editor_row, orient="vertical", command=self.text.yview)
scroll_x = ttk.Scrollbar(self.frame, orient="horizontal", command=self.text.xview)
self.text.configure(yscrollcommand=scroll_y.set, xscrollcommand=scroll_x.set)
scroll_y.pack(side="right", fill="y")
self.text.pack(side="left", fill="both", expand=True)
scroll_x.pack(fill="x")
self.highlighter = SyntaxHighlighter(self.text)
self.autocomplete = AutoComplete(self.text)
self.text.bind("<KeyRelease>", self._on_change)
self.text.bind("<Tab>", self._on_tab)
self.text.bind("<Return>", self._auto_indent)
self.text.bind("<Control-z>", lambda e: self.text.edit_undo())
self.text.bind("<Control-y>", lambda e: self.text.edit_redo())
self.text.bind("<Control-slash>", self._toggle_comment)
if filename and os.path.exists(filename):
self.load_file()
def _tab_label(self):
name = os.path.basename(self.filename) if self.filename else "Untitled"
return f" {name} "
def _on_change(self, event=None):
self.highlighter.highlight()
self.line_bar.redraw()
if not self.modified:
self.modified = True
idx = self.notebook.index(self.frame)
name = os.path.basename(self.filename) if self.filename else "Untitled"
self.notebook.tab(idx, text=f" ● {name} ")
def _on_tab(self, event):
self.text.insert("insert", " ")
return "break"
def _auto_indent(self, event):
idx = self.text.index("insert")
line = idx.split(".")[0]
line_text = self.text.get(f"{line}.0", f"{line}.end")
indent = re.match(r'^(\s*)', line_text).group(1)
if line_text.rstrip().endswith(":"):
indent += " "
self.text.insert("insert", "\n" + indent)
self.line_bar.redraw()
return "break"
def _toggle_comment(self, event):
try:
start = self.text.index("sel.first linestart")
end = self.text.index("sel.last lineend")
except tk.TclError:
start = self.text.index("insert linestart")
end = self.text.index("insert lineend")
lines = self.text.get(start, end).split("\n")
all_commented = all(l.lstrip().startswith("#") for l in lines if l.strip())
new_lines = []
for line in lines:
if all_commented:
new_lines.append(re.sub(r'^(\s*)#\s?', r'\1', line, count=1))
else:
new_lines.append(re.sub(r'^(\s*)', r'\1# ', line, count=1))
self.text.delete(start, end)
self.text.insert(start, "\n".join(new_lines))
return "break"
def load_file(self):
try:
with open(self.filename, "r", encoding="utf-8") as f:
content = f.read()
self.text.delete("1.0", "end")
self.text.insert("1.0", content)
self.highlighter.highlight()
self.line_bar.redraw()
self.modified = False
except Exception as e:
messagebox.showerror("Error", str(e))
def save_file(self):
if not self.filename:
self.filename = filedialog.asksaveasfilename(
defaultextension=".py",
filetypes=[("Python", "*.py"), ("All", "*.*")]
)
if not self.filename:
return False
try:
with open(self.filename, "w", encoding="utf-8") as f:
f.write(self.text.get("1.0", "end-1c"))
self.modified = False
idx = self.notebook.index(self.frame)
name = os.path.basename(self.filename)
self.notebook.tab(idx, text=f" {name} ")
return True
except Exception as e:
messagebox.showerror("Error", str(e))
return False
def get_content(self):
return self.text.get("1.0", "end-1c")
# ─────────────────────────── Terminal Panel ───────────────────────────────
class TerminalPanel(tk.Frame):
def __init__(self, parent):
super().__init__(parent, bg="#1e2127")
self.process = None
self._build()
def _build(self):
toolbar = tk.Frame(self, bg="#21252b")
toolbar.pack(fill="x")
tk.Label(toolbar, text=" Terminal / Output", bg="#21252b",
fg="#636d83", font=("Consolas", 10)).pack(side="left", pady=4)
tk.Button(toolbar, text="✕ Clear", bg="#21252b", fg="#636d83",
relief="flat", font=("Consolas", 10), cursor="hand2",
command=self.clear).pack(side="right", padx=8)
tk.Button(toolbar, text="⏹ Stop", bg="#21252b", fg="#e06c75",
relief="flat", font=("Consolas", 10), cursor="hand2",
command=self.stop).pack(side="right")
self.output = tk.Text(self, bg="#1e2127", fg="#abb2bf",
font=("Consolas", 11), relief="flat",
state="disabled", wrap="word", padx=8, pady=6,
insertbackground="white")
sb = ttk.Scrollbar(self, command=self.output.yview)
self.output.configure(yscrollcommand=sb.set)
sb.pack(side="right", fill="y")
self.output.pack(fill="both", expand=True)
self.output.tag_configure("error", foreground="#e06c75")
self.output.tag_configure("success", foreground="#98c379")
self.output.tag_configure("info", foreground="#61afef")
self.output.tag_configure("prompt", foreground="#e5c07b")
# stdin row
input_row = tk.Frame(self, bg="#21252b")
input_row.pack(fill="x")
tk.Label(input_row, text=" >>> ", bg="#21252b",
fg="#98c379", font=("Consolas", 11)).pack(side="left")
self.stdin_var = tk.StringVar()
self.stdin_entry = tk.Entry(input_row, textvariable=self.stdin_var,
bg="#21252b", fg="#abb2bf",
insertbackground="white",
relief="flat", font=("Consolas", 11))
self.stdin_entry.pack(fill="x", expand=True, padx=4, pady=4)
self.stdin_entry.bind("<Return>", self._send_stdin)
self._write("PyIDE Terminal ready.\n", "info")
self._write("Click ▶ Run or press Ctrl+R to execute your script.\n\n", "info")
def _write(self, text, tag=None):
self.output.configure(state="normal")
if tag:
self.output.insert("end", text, tag)
else:
self.output.insert("end", text)
self.output.see("end")
self.output.configure(state="disabled")
def run_code(self, code, filename=None):
self.stop()
self.clear()
self._write(f"▶ Running {filename or 'script'}...\n", "prompt")
# Write to temp file so relative imports work
if filename and os.path.exists(filename):
script_path = filename
cwd = os.path.dirname(filename)
else:
tmp = tempfile.NamedTemporaryFile(suffix=".py", delete=False, mode="w", encoding="utf-8")
tmp.write(code)
tmp.flush()
tmp.close()
script_path = tmp.name
cwd = os.getcwd()
def execute():
try:
self.process = subprocess.Popen(
[sys.executable, "-u", script_path],
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
stdin=subprocess.PIPE, text=True, cwd=cwd,
bufsize=1
)
# Stream stdout
for line in iter(self.process.stdout.readline, ''):
self.output.after(0, self._write, line)
# Stderr
err = self.process.stderr.read()
if err:
self.output.after(0, self._write, err, "error")
self.process.wait()
code_ret = self.process.returncode
msg = f"\n✓ Finished (exit 0)\n" if code_ret == 0 else f"\n✗ Exited with code {code_ret}\n"
tag = "success" if code_ret == 0 else "error"
self.output.after(0, self._write, msg, tag)
except Exception as e:
self.output.after(0, self._write, f"Error: {e}\n", "error")
finally:
self.process = None
threading.Thread(target=execute, daemon=True).start()
def _send_stdin(self, event=None):
if self.process and self.process.stdin:
try:
text = self.stdin_var.get() + "\n"
self.process.stdin.write(text)
self.process.stdin.flush()
self._write(f" ↳ {text}", "prompt")
self.stdin_var.set("")
except Exception:
pass
def stop(self):
if self.process:
try:
self.process.terminate()
except Exception:
pass
def clear(self):
self.output.configure(state="normal")
self.output.delete("1.0", "end")
self.output.configure(state="disabled")
# ─────────────────────────── File Tree ────────────────────────────────────
class FileTree(tk.Frame):
def __init__(self, parent, on_open):
super().__init__(parent, bg="#21252b")
self.on_open = on_open
self.root_path = None
self._build()
def _build(self):
header = tk.Frame(self, bg="#21252b")
header.pack(fill="x")
tk.Label(header, text=" EXPLORER", bg="#21252b",
fg="#636d83", font=("Consolas", 10)).pack(side="left", pady=6)
self.tree = ttk.Treeview(self, show="tree", selectmode="browse")
self.tree.pack(fill="both", expand=True)
self.tree.bind("<Double-1>", self._on_double_click)
sb = ttk.Scrollbar(self, command=self.tree.yview)
self.tree.configure(yscrollcommand=sb.set)
sb.pack(side="right", fill="y")
style = ttk.Style()
style.configure("Treeview", background="#21252b", foreground="#abb2bf",
fieldbackground="#21252b", borderwidth=0, font=("Consolas", 11))
style.map("Treeview", background=[("selected", "#2c313c")])
def load_folder(self, path):
self.root_path = path
self.tree.delete(*self.tree.get_children())
root_node = self.tree.insert("", "end", text=f" {os.path.basename(path)}",
open=True, values=[path])
self._populate(root_node, path)
def _populate(self, parent_node, path):
try:
entries = sorted(os.scandir(path), key=lambda e: (not e.is_dir(), e.name.lower()))
for entry in entries:
if entry.name.startswith(".") or entry.name == "__pycache__":
continue
icon = "📁" if entry.is_dir() else "🐍" if entry.name.endswith(".py") else "📄"
node = self.tree.insert(parent_node, "end",
text=f" {icon} {entry.name}",
values=[entry.path])
if entry.is_dir():
self.tree.insert(node, "end", text="") # placeholder
for node in self.tree.get_children(parent_node):
self.tree.tag_bind(node, "<<TreeviewOpen>>", lambda e, n=node: self._expand(n))
except PermissionError:
pass
def _expand(self, node):
children = self.tree.get_children(node)
if len(children) == 1 and self.tree.item(children[0])["text"] == "":
self.tree.delete(children[0])
path = self.tree.item(node)["values"][0]
self._populate(node, path)
def _on_double_click(self, event):
sel = self.tree.selection()
if sel:
path = self.tree.item(sel[0])["values"]
if path:
path = path[0]
if os.path.isfile(path):
self.on_open(path)
# ─────────────────────────── Status Bar ───────────────────────────────────
class StatusBar(tk.Frame):
def __init__(self, parent):
super().__init__(parent, bg="#21252b", pady=2)
self.lbl_file = tk.Label(self, text=" No file", bg="#528bff", fg="white",
font=("Consolas", 10), padx=8)
self.lbl_file.pack(side="left")
self.lbl_pos = tk.Label(self, text=" Ln 1, Col 1", bg="#21252b", fg="#636d83",
font=("Consolas", 10))
self.lbl_pos.pack(side="left", padx=8)
self.lbl_lang = tk.Label(self, text="Python 3", bg="#21252b", fg="#636d83",
font=("Consolas", 10))
self.lbl_lang.pack(side="right", padx=8)
self.lbl_enc = tk.Label(self, text="UTF-8", bg="#21252b", fg="#636d83",
font=("Consolas", 10))
self.lbl_enc.pack(side="right", padx=8)
def update(self, filename=None, line=1, col=1):
if filename:
self.lbl_file.config(text=f" {os.path.basename(filename)}")
self.lbl_pos.config(text=f" Ln {line}, Col {col}")
# ─────────────────────────── Main IDE App ─────────────────────────────────
class PyIDE(tk.Tk):
def __init__(self):
super().__init__()
self.title("PyIDE — Python IDE")
self.geometry("1200x750")
self.configure(bg="#282c34")
self.tabs = {} # widget -> EditorTab
self._load_icon()
self._build_ui()
self._build_menus()
self._bind_shortcuts()
self.new_file() # open blank tab on start
def _load_icon(self):
try:
icon = tk.PhotoImage(data="""
R0lGODlhEAAQAIABAAAAAP///yH5BAEKAAEALAAAAAAQABAAAAIjjI+py+0Po5y02ouz3rz7D4bi
SJbmiabqyrbuC8fyTNcFADs=
""")
self.iconphoto(True, icon)
except Exception:
pass
def _build_ui(self):
self.paned_main = ttk.PanedWindow(self, orient="horizontal")
self.paned_main.pack(fill="both", expand=True)
# Left: file tree
self.file_tree = FileTree(self.paned_main, self.open_file)
self.paned_main.add(self.file_tree, weight=0)
self.file_tree.configure(width=200)
# Right side
right = tk.Frame(self.paned_main, bg="#282c34")
self.paned_main.add(right, weight=1)
self.paned_vert = ttk.PanedWindow(right, orient="vertical")
self.paned_vert.pack(fill="both", expand=True)
# Editor notebook
style = ttk.Style(self)
style.theme_use("clam")
style.configure("TNotebook", background="#21252b", borderwidth=0, tabmargins=0)
style.configure("TNotebook.Tab", background="#21252b", foreground="#636d83",
font=("Consolas", 11), padding=[8, 4])
style.map("TNotebook.Tab",
background=[("selected", "#282c34")],
foreground=[("selected", "#abb2bf")])
style.configure("TPanedwindow", background="#21252b")
style.configure("Sash", sashthickness=4, background="#3e4452")
style.configure("TScrollbar", background="#3e4452", troughcolor="#21252b",
arrowcolor="#636d83", borderwidth=0)
self.notebook = ttk.Notebook(self.paned_vert)
self.paned_vert.add(self.notebook, weight=3)
# Terminal
self.terminal = TerminalPanel(self.paned_vert)
self.paned_vert.add(self.terminal, weight=1)
# Status bar
self.status = StatusBar(right)
self.status.pack(fill="x", side="bottom")
self.notebook.bind("<<NotebookTabChanged>>", self._on_tab_change)
def _build_menus(self):
menubar = tk.Menu(self, bg="#21252b", fg="#abb2bf",
activebackground="#2c313c", activeforeground="#abb2bf",
relief="flat", bd=0)
self.config(menu=menubar)
def menu(label):
m = tk.Menu(menubar, tearoff=0, bg="#21252b", fg="#abb2bf",
activebackground="#2c313c", activeforeground="#abb2bf",
relief="flat", bd=0)
menubar.add_cascade(label=label, menu=m)
return m
file_m = menu("File")
file_m.add_command(label="New File Ctrl+N", command=self.new_file)
file_m.add_command(label="Open File... Ctrl+O", command=self.open_file_dialog)
file_m.add_command(label="Open Folder... Ctrl+K", command=self.open_folder)
file_m.add_separator()
file_m.add_command(label="Save Ctrl+S", command=self.save_file)
file_m.add_command(label="Save As... Ctrl+Shift+S", command=self.save_as)
file_m.add_separator()
file_m.add_command(label="Close Tab Ctrl+W", command=self.close_tab)
file_m.add_command(label="Exit", command=self.quit)
run_m = menu("Run")
run_m.add_command(label="Run File Ctrl+R", command=self.run_current)
run_m.add_command(label="Stop Ctrl+C", command=self.terminal.stop)
run_m.add_command(label="Clear Terminal", command=self.terminal.clear)
edit_m = menu("Edit")
edit_m.add_command(label="Undo Ctrl+Z", command=lambda: self._current_text().edit_undo())
edit_m.add_command(label="Redo Ctrl+Y", command=lambda: self._current_text().edit_redo())
edit_m.add_separator()
edit_m.add_command(label="Toggle Comment Ctrl+/", command=self._toggle_comment)
edit_m.add_separator()
edit_m.add_command(label="Select All Ctrl+A",
command=lambda: self._current_text().tag_add("sel", "1.0", "end"))
view_m = menu("View")
view_m.add_command(label="Increase Font Ctrl+=", command=lambda: self._zoom(1))
view_m.add_command(label="Decrease Font Ctrl+-", command=lambda: self._zoom(-1))
help_m = menu("Help")
help_m.add_command(label="About PyIDE", command=self._about)
def _bind_shortcuts(self):
self.bind("<Control-n>", lambda e: self.new_file())
self.bind("<Control-o>", lambda e: self.open_file_dialog())
self.bind("<Control-k>", lambda e: self.open_folder())
self.bind("<Control-s>", lambda e: self.save_file())
self.bind("<Control-S>", lambda e: self.save_as())
self.bind("<Control-w>", lambda e: self.close_tab())
self.bind("<Control-r>", lambda e: self.run_current())
self.bind("<Control-equal>", lambda e: self._zoom(1))
self.bind("<Control-minus>", lambda e: self._zoom(-1))
self.bind("<Control-slash>", lambda e: self._toggle_comment())
def _current_tab(self):
try:
widget = self.notebook.nametowidget(self.notebook.select())
return self.tabs.get(widget)
except Exception:
return None
def _current_text(self):
tab = self._current_tab()
return tab.text if tab else None
def _on_tab_change(self, event):
tab = self._current_tab()
if tab:
self.status.update(filename=tab.filename)
tab.text.bind("<KeyRelease>", self._update_status)
tab.text.bind("<ButtonRelease>", self._update_status)
def _update_status(self, event=None):
tab = self._current_tab()
if tab:
pos = tab.text.index("insert")
ln, col = pos.split(".")
self.status.update(filename=tab.filename, line=int(ln), col=int(col)+1)
def new_file(self):
tab = EditorTab(self.notebook)
self.tabs[tab.frame] = tab
self.notebook.select(tab.frame)
def open_file(self, path=None):
if not path:
return
# Check if already open
for widget, tab in self.tabs.items():
if tab.filename == path:
self.notebook.select(widget)
return
tab = EditorTab(self.notebook, filename=path)
self.tabs[tab.frame] = tab
self.notebook.select(tab.frame)
self.status.update(filename=path)
def open_file_dialog(self):
path = filedialog.askopenfilename(
filetypes=[("Python", "*.py"), ("All files", "*.*")]
)
if path:
self.open_file(path)
def open_folder(self):
path = filedialog.askdirectory()
if path:
self.file_tree.load_folder(path)
def save_file(self):
tab = self._current_tab()
if tab:
tab.save_file()
self.status.update(filename=tab.filename)
def save_as(self):
tab = self._current_tab()
if tab:
tab.filename = None
tab.save_file()
def close_tab(self):
tab = self._current_tab()
if not tab:
return
if tab.modified:
ans = messagebox.askyesnocancel("Unsaved", "Save before closing?")
if ans is None:
return
if ans:
if not tab.save_file():
return
self.notebook.forget(tab.frame)
del self.tabs[tab.frame]
def run_current(self):
tab = self._current_tab()
if not tab:
return
code = tab.get_content()
# Auto-save before run
if tab.filename and tab.modified:
tab.save_file()
self.terminal.run_code(code, filename=tab.filename)
def _toggle_comment(self):
tab = self._current_tab()
if tab:
tab._toggle_comment(None)
def _zoom(self, delta):
for widget, tab in self.tabs.items():
f = tab.text.cget("font")
try:
fnt = font.Font(font=f)
size = fnt.cget("size") + delta
size = max(8, min(32, size))
tab.text.configure(font=("Consolas", size))
except Exception:
pass
def _about(self):
messagebox.showinfo("About PyIDE",
"PyIDE — A Python IDE built in Python\n\n"
"Features:\n"
" • Syntax highlighting\n"
" • Auto-indentation\n"
" • Autocomplete\n"
" • Integrated terminal\n"
" • File explorer\n"
" • Multi-tab editing\n\n"
"Built with Python + tkinter only.")
# ─────────────────────────── Entry Point ──────────────────────────────────
if __name__ == "__main__":
app = PyIDE()
app.mainloop()