'Is there any simpler way to make a text editor in python with line counter?

I am working on a beta of a program that I will later publish as open source software.

I want to ask you if there is any simple way currently to make a text editor with line counter but loaded in a python tkinter frame. I was looking at this answer from 8 years ago (Tkinter adding line number to text widget), however I'm having a hard time understanding how it works and I'm also having trouble trying to adapt it to my code.

I would greatly appreciate your comments.

This is my GUI



Solution 1:[1]

A low tech solution is to have a function run once or twice a second that gets the number of lines and updates a label.

For example, assuming you have a text widget named editor and a label named line_count, the function might look something like this:

def update_line_count():
    lines = editor.index("end-1c").split(".")[0]
    line_count.configure(text=f"lines: {lines}")
    root.after(500, update_line_count)

If you call that function once, it will continue to run every 500ms for as long as the program is running. The function itself just takes fractions of a millisecond to run so it doesn't add a noticeable load.

Here's a complete working example:

import tkinter as tk

root = tk.Tk()
editor_frame = tk.Frame(root)
status_frame = tk.Frame(root)

status_frame.pack(side="bottom", fill="x")
editor_frame.pack(side="top", fill="both", expand=True)

scrollbar = tk.Scrollbar(editor_frame, orient="vertical")
editor = tk.Text(editor_frame, yscrollcommand=scrollbar.set, wrap="word")
scrollbar.configure(command=editor.yview)

scrollbar.pack(side="right", fill="y")
editor.pack(side="left", fill="both", expand=True)

line_count = tk.Label(status_frame, width=12, bd=1, relief="sunken")
line_count.pack(side="right")

def update_line_count():
    lines = editor.index("end-1c").split(".")[0]
    line_count.configure(text=f"lines: {lines}")
    editor.after(500, update_line_count)

update_line_count()

root.mainloop()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bryan Oakley