0

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

  • Are you asking for a _count_ (ie: a label that says something like "lines: 42") or are you wanting to see line numbers? If you want line numbers, you'll have to show us what you've tried from the other solution and explain why it doesn't work for you. – Bryan Oakley Feb 04 '22 at 22:30

1 Answers1

0

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()

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685