简体   繁体   中英

Python 3 Tkinter | Change color/style for words in between ':' in Text Widget

Let's say we have this text:

text = "You don't need to try to find hidden meaning:\nin this text :sun_with_face:!\nthis text : does not have any :meaning :D"

Now notice the :sun_with_face: in the text above? That's what I am trying to get somehow highlighted by changing the boldness and the color of the Text Widget to that particular section.

Issue:

  • How to filter the text for :these_words: ? You may notice that those are emoji.demojized() emoji so an optional solution would be to highlight all words that are in the emoji.UNICODE_EMOJI list but I feel that it will tax on the resources and time a lot (since the list contains over 1000 items)

  • How to highlight the wanted stuff. Even though we might somehow solve the first issue, these demojized emoji are in the middle of the text...

Edit

Just to clarify: I know how to highlight the text from this question . I just need to know the location of the word to high light it, which is the tricky part. Also the :sun_with_face:. It can be anything as long as its open and closed with ':' and in-between there are no spaces ( ) and newlines ( \\n ).

I think what you're asking is how to apply a highlight to text that begins with a colon, has some sort span of text, and ends with a colon. You can find text that matches that pattern with the text widget search method, and you can apply the highlighting by using the tag feature of text widgets.

Since you are wanting to search against a pattern, you need to use a regular expression search. You do this by setting regexp to True when you call the search method. Because the pattern can be any length, you also need to pass in a variable so that tkinter can return how many characters it matched. You can use this information to apply the highlighting.

Note: when using regular expression searches, the expression must follow the Tcl regular expression syntax , not the python one. There are some subtle differences.

Here's an example that finds all matches of a colon followed immediately by the shortest group of non-whitespace characters, followed by a colon. It then adds the tag "highlight" to each match:

countVar = tk.IntVar()
start_index = "1.0"
while start_index:
    index = text_widget.search(r':\S+?:', start_index, stopindex="end",
                               count=countVar, regexp=True)
    if index:
        # ie: a match was found
        end_index = "{} + {} chars".format(index, countVar.get())
        text_widget.tag_add("highlight", index, end_index)
        start_index = end_index
    else:
        start_index = None

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM