Set specific words in ScrolledText red

290 Views Asked by At

i need to find and highlight with color OR bold specific words in string.

i thought on doing like this

word to put in red=is:

var="my string is that should is appear with the word flame is in red is"

varf=var.replace(" is ","\033[1;32;40m  is ")

but this dont work on tkinter ScrolledText, just in terminal :s

is there a way to do this in a tkinter ScrolledText widget?

Word will appear in diferent places in string so its hard to do the config.tag because i have to specify the interval of characters in the string to color.

my code

def checkval(e, spec0, spec1, spec2, spec3, spec4, spec5):
        e.widget.insert("1.0", PLACEHOLDER if e.widget.get("1.0", "end-1c") == "" else "")
        reqlidst=(spec0, spec1, spec2, spec3, spec4, spec5)
        textlabl=""
        for x in reqlidst:
   
            if len(x)>1:
                #print("selected text: '%s'" % e.widget.get(SEL_FIRST, SEL_LAST))
                if x.upper() in e.widget.get("1.0", "end-1c").upper():
                    if len(textlabl)>1:
                        textlabl = textlabl + "- " + x.replace(" ", "").upper() + "  " + html.unescape('✔')+"\n\n"
                    else:
                        textlabl = "- " + x.replace(" ", "").upper() + "  " + html.unescape('✔')+"\n\n"
                else:
                    if len(textlabl) > 1:
                        textlabl =textlabl + "- " + x.replace(" ", "").lower() + "  " + html.unescape('✘')+"\n\n"
                    else:
                        textlabl = "- " + x.replace(" ", "").lower() + "  " + html.unescape('✘')+"\n\n"
        e.widget.my_var_expected.set(textlabl)

reqlidst are the word to search for and show in red

How to change the color of certain words in the tkinter text widget? doesnt answer my question :/

1

There are 1 best solutions below

0
On

There is a tag method in the Tkinter text. This allows you to mark certain parts. I have prepared a small example for you, where the Text-Widget dynamically recognizes the words Hello and Jonny.

In principle, you only really need to be familiar with the indexes.

from tkinter import Text,  Button, Tk

root = Tk()


def output(event):

    length = len("Hello")
    val = len(txt.get("1.0", "end-1c"))
    for x in range(len(txt.get("1.0", "end-1c"))):
        if "Hello" in txt.get(f"1.{x}", "end-1c") or "Jonny" in txt.get(f"1.{x}", "end-1c") :
            val = x
    vals = str(val + length)
    txt.tag_add("Hello", f"1.{str(val)}", f"1.{vals}")
    txt.tag_config("Hello", background="red", foreground="white")

txt = Text(root)
txt.grid(columnspan=3)

root.bind("<Key>", output)

root.mainloop()

enter image description here

Please note that I did not write a whole program for each new line.

For example, to make it more dynamic, you could change the indexes. So you can implement that for each line.

My example is for the first line only.

greeting