Panone
Panone

Reputation: 3

Tkinter Text convert index to char position

Is there a way to efficiently calculate the char position from an index in the Tk Text widget?

As example:

„This is a dummy text displayed in Tk Text“

Index 1.11 (the „d“) would translate to 11

Thanks a lot for feedback!

Upvotes: 0

Views: 392

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385980

The method count will return the number of characters or lines or indices between two indexes. The default is to return "indices" which might be what you want. The values you want are added as additional positional arguments.

The function returns a tuple with the number of elements requested. For example, requesting "chars" will return a tuple with one value representing the number of characters.

chars = text.count("1.0", "1.11", "chars")[0]
assert chars==11

These are the options:

  • chars - count all characters, whether elided or not. Do not count embedded windows or images.
  • displaychars - count all non-elided characters.
  • displayindices - count all non-elided characters, windows and images.
  • displaylines - count all display lines (i.e. counting one for each time a line wraps) from the line of the first index up to, but not including the display line of the second index.
  • indices - count all characters and embedded windows or images
  • lines - count all logical lines (irrespective of wrapping) from the line of the first index up to, but not including the line of the second index.
  • xpixels - count the number of horizontal pixels from the first pixel of the first index to (but not including) the first pixel of the second index.
  • ypixels - count the number of vertical pixels from the first pixel of the first index to (but not including) the first pixel of the second index.

Upvotes: 1

Related Questions