Home > front end >  how to highlight text in tkinter using for loops
how to highlight text in tkinter using for loops

Time:09-28

trying to highlight some part of a text using tkinter tag_add widget. just not sure how to reference start and end index in tkinter. could someone tell me how to resolve this issue? without using for looops it is going to be startindex: 1.0, endindex:1.3 but how I can reference to those indexes when it comes to for loops?`


from tkinter import *
window = Tk()
window.title('highlight')
x='ABCDEFG'
text=Text(window, width=20, height=5, font=('Calibri 12'))
text.insert(INSERT, x)
for i in range(len(x)):
             text.tag_add('highlight', x[i], x[i 1])
text.tag_configure("highlight",background="OliveDrab1", foreground="black")
text.pack()
window.mainloop()

CodePudding user response:

Since you're inserting code at the insertion point, you can get the index with the index method. For example, to get the insertion point immediately before inserting the string you can do something like this:

start_index = text.index("INSERT")

The above will return a string of the form . (eg: "1.0", "2.0", "3.42", etc).

You can also add modifiers to an index. For example, if you want to go from "12.0" to "12.1" without hard-coding "12.1", you can do something like this:

text.tag_add("highlight", "12.0", "12.0 1c")

The latter is shorthand for "12.0 plus one character".

While it's very inefficient to do it this way, you could write your loop like so:

start_index = text.index(INSERT)
text.insert(INSERT, x)
for i in range(len(x)):
    text.tag_add('highlight',
                 f"{start_index} {i}c",
                 f"{start_index} {i 1}c"
)

The more efficient solution would be to skip the loop and highlight the whole line at once:

text.tag_add('highlight',
             f"{start_index}",
             f"{start_index} {len(x)}c"
)

And finally, the most efficient would be to add the tag at the time of the insert statement:

text.insert(INSERT, x, 'highlight')

CodePudding user response:

Thanks Bryan, let me include my real codes here so, you get a better idea what I want to do in Tkinter. this code looks for consecutive numbers that equal to a specific sum. I want Tkinter to show the highlit as a box or label as jupyter output like attached pic.I really need this and will appreciate if you help me. here is my code in Jupiter:

user = 'ABCDEFGHIJ'
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for i in range(len(x)):
    for j in range(len(x)):
            y = sum(x[i:j 1])
            if y == 20:
                print(user.replace(user[i:j 1], '\033[44;33m{}\033[m'.format(user[i:j 1])))```

[enter image description here][1]
       


  [1]: https://i.stack.imgur.com/mb4AI.png
  • Related