11

I have a Tkinter Text widget, and I'd like to know how many lines it contains.

I know of the text.cget("height") method, however that only tells me how many lines are displayed. I'd like to know how many lines there are total.

I'm using this info to try to make my own custom scrollbar, so any help would be much appreciated.

nbro
  • 15,395
  • 32
  • 113
  • 196
rectangletangle
  • 50,393
  • 94
  • 205
  • 275
  • 1
    If you need the total display lines, check out my answer here for help (and change start and end accordingly, and edit for the fact that I was ultimately answering for remaining lines instead of total): http://stackoverflow.com/questions/29428515/whats-the-most-efficient-way-to-get-a-tkinter-text-widgets-total-display-lines – Brōtsyorfuzthrāx Apr 03 '15 at 09:07

1 Answers1

15

Use the index method to find the value of 'end' which is the position just after the last character in the buffer.

>>> text_widget.index('end')  # returns line.column 
'3.0'

>>> int(text_widget.index('end').split('.')[0]) - 1  # returns line count
2 

Update per Bryan Oakley's comment:

>>> int(text_widget.index('end-1c').split('.')[0])  # returns line count
2 
Steven Rumbalski
  • 44,786
  • 9
  • 89
  • 119
  • 6
    You could also use `'end-1c'` to avoid having to subtract 1 (though the value after the "." will be whatever number of characters are on that last line rather than zero) – Bryan Oakley Jan 05 '11 at 22:10
  • Thanks, that helps a ton! When I'm done with my current project I'll probably release some of the widgets I made as an extension for Tkinter. If there's an interest. – rectangletangle Jan 05 '11 at 22:22