Search code examples
tkintertextcountwidgetline

Tkinter widget Text : count lines


In this short program I would like to know how many lines the messages needs to be displayed. The problem is that rather than to answer me that it needs 3 lines here, it gives me 1. Why ? I tried different solutions found about this topic, but no one was working, each of them had som issues (it was not counting the number of lines as here).

I use Python 3.9.2 on Windows 10

Thanks for the help !!!

from tkinter import *

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

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

root.mainloop()

Solution

  • Adapted from here:

    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.update()
    
    # Note `text.count("0.0", "end", "displaylines")` returns a tuple like this: `(3, )`
    result = text.count("0.0", "end", "displaylines")[0]
    print(result)
    
    root.mainloop()