Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()

>Solution :

"2.04" is not valid. It will work, but something like "2.08" won’t since 08 is an invalid octal number.

The text index 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"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading