33from tkinter import simpledialog
44
55# Main Window
6+
67root = tk .Tk ()
78root .title ("Python Text Editor" )
89
@@ -75,8 +76,7 @@ def paste():
7576 # If there's no selected text, just insert at the current position
7677 text .insert (tk .INSERT , selected_text )
7778 except tk .TclError :
78- # This catches the exception if there's no text in the clipboard
79- pass
79+ pass # Catch the exception if there's no text in the clipboard
8080
8181def cut ():
8282 if text .tag_ranges ('sel' ):
@@ -123,6 +123,7 @@ def open_find_replace_dialog():
123123 dialog = FindReplaceDialog (root )
124124 root .wait_window (dialog ) # This will wait until the dialog window is closed.
125125
126+
126127# Define the add-shortcut function
127128
128129def add_shortcut (key , func ):
@@ -141,6 +142,7 @@ def add_shortcut(key, func):
141142add_shortcut ('<Control-l>' , toggle_line_numbers )
142143
143144# File Menu
145+
144146menu = tk .Menu (root )
145147root .config (menu = menu )
146148
@@ -157,6 +159,7 @@ def add_shortcut(key, func):
157159file_menu .add_command (label = "Exit" , command = root .quit )
158160
159161# Edit Menu
162+
160163edit_menu = tk .Menu (menu , tearoff = 0 )
161164menu .add_cascade (label = "Edit" , menu = edit_menu )
162165edit_menu .add_command (label = "Undo" , command = lambda : text .edit_undo (), accelerator = "Ctrl+Z" )
@@ -172,22 +175,28 @@ def add_shortcut(key, func):
172175edit_menu .add_command (label = "Find and Replace" , command = open_find_replace_dialog , accelerator = "Ctrl+F" )
173176
174177# Line Numbers
178+
175179line_numbers = LineNumberCanvas (root , width = 30 )
176180line_numbers .pack (side = "left" , fill = "y" )
177181
178182# Text Area
183+
179184text = tk .Text (root , wrap = tk .WORD )
180185text .pack (expand = True , fill = "both" )
181186
182187# Enable Undo/Redo Feature
188+
183189text .config (undo = True )
184190
185191# Attach text widget to line numbers
192+
186193line_numbers .attach (text )
187194
188195# Redraw line numbers on text change
196+
189197text .bind ("<KeyRelease>" , lambda event : line_numbers .redraw ())
190198text .bind ("<MouseWheel>" , lambda event : line_numbers .redraw ())
191199
192200# GUI Main Loop
201+
193202root .mainloop ()
0 commit comments