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