TomSchimansky / CustomTkinter

A modern and customizable python UI-library based on Tkinter
MIT License
10.8k stars 1.03k forks source link

Line numbers for CTkTextBox #2393

Closed vihaanmody1 closed 2 months ago

vihaanmody1 commented 2 months ago

Hello,

I am making an editor which will use CTkTextBox. Is there a way to add line numbers to it?

Thank you

FaheemM1020 commented 2 months ago

Have a look at this: https://pypi.org/project/tklinenums/

Akascape commented 2 months ago

@vihaanmody1 Here is the implementation of tklinenums: image

import customtkinter
from tklinenums import TkLineNumbers

class AddLineNums(TkLineNumbers):
    """
    Class for adding line numbers in CTkTextbox using TkLineNumbers
    By Akascape
    """
    def __init__(self,
                 master,
                 text_color=None,
                 justify="left",
                 padx=35,
                 **kwargs):

        self.master = master
        self.text_color = self.master.cget("border_color") if text_color is None else text_color
        self.fg_color = self.master.cget("fg_color")

        customtkinter.windows.widgets.appearance_mode.CTkAppearanceModeBaseClass.__init__(self)

        super().__init__(self.master, self.master, justify=justify,
                         colors=(self.master._apply_appearance_mode(self.text_color),
                                 self.master._apply_appearance_mode(self.fg_color)),
                         relief="flat", **kwargs)

        padding = self.master.cget("border_width") + self.master.cget("corner_radius")

        super().grid(row=0, column=0, sticky="nsw", padx=(padding,0), pady=padding-1)

        self.master._textbox.grid_configure(padx=(padx, 0))
        self.master._textbox.lift()
        self.master._textbox.configure(yscrollcommand=self.set_scrollbar)
        self.master._textbox.bind("<<ContentChanged>>", self.redraw, add=True)
        self.master.bind("<Key>", lambda e: self.after(10, self.redraw), add=True)

    def set_scrollbar(self, x,y):
        self.redraw(x,y)
        self.master._y_scrollbar.set(x,y)

    def _set_appearance_mode(self, mode_string):
        self.colors = (self.master._apply_appearance_mode(self.text_color),
                       self.master._apply_appearance_mode(self.fg_color))

# Usage
root = customtkinter.CTk()

textbox = customtkinter.CTkTextbox(root, border_width=1)
textbox.pack(fill="both", expand=True, padx=10, pady=10)

for i in range(50):
    textbox.insert("end", f"Line {i+1}\n")

AddLineNums(textbox) # Just add this line for any ctktextbox

root.mainloop()
vihaanmody1 commented 2 months ago

Thank You !!