How do you make the tkinter text widget recognise lines in the index?

Question:

I’m working on highlighting chosen parts of a text green in a text widget in Tkinter.

To my understanding, on Tkinter the index for the second line, fourth character of a text would be 2.04. For some reason, it’s not recognising a new line and the decimal number keeps increasing into the hundreds so I’m struggling to highlight words once the total characters of the text exceed 99. When it does, it highlights lots of text after the chosen word in green.

I’ve set the max width of the text widget to 99 characters to make the index create lines but but it’s still not doing anything.

For clarification, I’m trying to highlight the word ‘calculates’ in green with this code.

from tkinter import *

window = Tk()
text_window = Text(window, height=10, width=99, wrap=WORD)
text_window.insert(INSERT, sample_text)
text_window.configure(state=DISABLED)
text_window.pack()

countVar = StringVar()
pos = text_window.search("calculates", "1.0", stopindex="end", count=countVar)
end_num = float(countVar.get()) / 100
position = float(pos)
print(position)
print(end_num)
end_point = position + end_num
text_window.tag_configure("search", background="green")
text_window.tag_add("search", pos, end_point)


window.mainloop()

Asked By: David R

||

Answers:

"2.04" is not valid. It will work, but something like "2.08" won’t since 08 is an invalid octal number. A text widget index must be string in the form of a valid integer, a period, and then another valid integer.

The text widget index also supports modifiers, so you can easily add or subtract characters. In your case it would look something like this:

end_point = f"{pos}+{countVar.get()}chars"

or

end_point = f"{pos}+{countVar.get()}c"
Answered By: Bryan Oakley
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.