Home > database >  Find position of wrapped text in a tkinter text element
Find position of wrapped text in a tkinter text element

Time:12-12

I need to find the location of the cursor in the text displayed in a tkinter text element, rather than its location in the text element's contents.

For example, if line 1 in a text element is wrapped, so it covers two lines, and the cursor is in the half of line 1 which was moved to a new line. If I got the position of the cursor, it would say the cursor was in line 1, however, it is displayed in the second line.

I would like to find the line the cursor is displayed in, rather than the line in the text that it is in.

Hopefuly this image explains my problem better

CodePudding user response:

I would like to find the line the cursor is displayed in, rather than the line in the text that it is in.

You can try using the count method to get the count of the number of displayed lines between the first character and the insertion point.

(lines,) = text.count("1.0", "insert", "displaylines")

For example, if the first line is short and then the next line wraps to two lines, and then there is a third line, there will be four display lines. If the cursor is on the last line, the above code will return 3

This is what the canonical tcl/tk documentation says about displayines:

"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. Therefore if they are both on the same display line, zero will be returned. By definition displaylines are visible and therefore this only counts portions of actual visible lines."

  • Related