'Tkinter - Counting lines in a Text widget with word wrapping

I'd like to know how to get the number of lines in a Tkinter Text widget that has word wrap enabled.

In this example, there are 3 lines in the text widget :

from Tkinter import *

root = Tk()
text = Text(root, width = 12, height = 5, wrap = WORD)
text.insert(END, 'This is an example text.')
text.pack()

root.mainloop()

But methods that work for non-wrapped text, like :

int(text_widget.index('end-1c').split('.')[0]) 

will return 1 instead of 3. Is there another method that would properly count wrapped lines (and return 3 in my example) ?

Thanks for your help !



Solution 1:[1]

I know this is very old but, I wanted to throw a possible current(2022) answer for those working with wrapping lines on windows 10.

import tkinter as tk


def inspect_wrapline(event=None):
  start = f"{tk.INSERT} linestart"
  end   = f"{tk.INSERT} lineend"
  counter = event.widget.count(start, end, "displaylines")
  
  print("number of lines after first line", counter)


  start = f"{tk.INSERT} display linestart"
  end   = f"{tk.INSERT} display lineend +1c"
  dline = event.widget.get(start, end)

  print("Text on the displayline", dline)


root_window = tk.Tk()
text_widget = tk.Text(root_window)
text_widget.pack()
text_widget.insert("This is an example text.")
text_widget.bind("<Control-l>", inspect_wrapline)

root_window.mainloop()

Output:

insert @ line 0: (2,) This is an

insert @ line 1: (2,) example

insert @ line 2: (2,) text.


Terminology:

Displayline: a single line of text from left to right in the widget viewing area.

Logic line: a string of text regardless of wraps. There is only 1 'logic line' in a line that wraps (or at least that is my understanding.).


Note:

Even though the option is a "displayline" it will yield a displayline even if it is not currently visible in the viewing area.


Hope this helps some wayward tkinter users trying to figure out wrapping lines.

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 Valthalin