Created
July 12, 2023 19:23
-
-
Save martinandersen3d/b66bb0dca8600b76611093a0bb284c36 to your computer and use it in GitHub Desktop.
Python Tkinter Code Editor with Line numbers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import tkinter as tk | |
from tkinter import ttk | |
class GridApp: | |
def __init__(self): | |
self.root = tk.Tk() | |
self.root.title("Grid Layout") | |
# Create the Text_Linenumber widget | |
self.text_linenum = tk.Text(self.root, width=5) | |
self.text_linenum.grid(row=0, column=0, sticky="ns", padx=(0, 20)) | |
# Configure the tag to align the text to the right | |
self.text_linenum.tag_configure("right_align", justify="right") | |
# Create the Text_Code widget | |
self.text_code = tk.Text(self.root) | |
self.text_code.grid(row=0, column=1, sticky="nsew") | |
# Create the Scrollbar widget | |
self.scrollbar_y = ttk.Scrollbar(self.root, command=self.text_code.yview) | |
self.scrollbar_y.grid(row=0, column=2, sticky="ns") | |
# Link the scrollbar to the Text_Code widget | |
# self.text_code.config(yscrollcommand=self.scrollbar_y.set) | |
self.text_code.config(yscrollcommand=self.handle_scroll_code_view) | |
# Configure the grid layout to expand the Text_Code widget | |
self.root.grid_rowconfigure(0, weight=1) | |
self.root.grid_columnconfigure(1, weight=1) | |
# Bind the on_scroll method to Text_Code widget's scroll event | |
self.text_code.bind("<MouseWheel>", self.on_scroll) | |
# Fill the Text_Code widget with lines of text | |
for x in range(9999): | |
print(x) | |
self.text_code.insert("end", "Line"+str(x) + "\n") | |
self.insert_linenumbers() | |
def run(self): | |
self.root.mainloop() | |
def on_scroll(self, *args): | |
# Method to be called when Text_Code is scrolled | |
print("Text_Code scrolled") | |
def handle_scroll_code_view(self, x0, x1): | |
print(x0, x1) | |
self.scrollbar_y.set(x0, x1) | |
self.text_linenum.yview_moveto(x0) | |
def insert_linenumbers(self): | |
# Clear the current line numbers | |
self.text_linenum.delete('1.0', 'end') | |
num_lines = self.text_code.get('1.0', 'end').count('\n') | |
# Insert line numbers in TextA | |
line_numbers = '\n'.join(str(i) for i in range(1, num_lines + 1)) | |
self.text_linenum.insert('1.0', line_numbers) | |
self.text_linenum.tag_add("right_align", "1.0", "end") | |
if __name__ == "__main__": | |
app = GridApp() | |
app.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment