Explain Tkinter text search method

前端 未结 2 1346
借酒劲吻你
借酒劲吻你 2020-11-29 12:26

I don\'t quite understand how text.search method works. For example there is a sentence: Today a red car appeared in the park. I need to find a red car

2条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-29 13:07

    The search method returns the index of the first match at or after the starting index, and optionally the number of characters that matched. You are responsible for highlighting what it found by using this information.

    For example, consider this search:

    countVar = tk.StringVar()
    pos = text.search("a red car", "1.0", stopindex="end", count=countVar)
    

    If a match is found, pos will contain the index of the first character of the match and countVar will contain the number of characters that matched. You can use this information to highlight the match by using an index of the form "index + N chars" or the shorthand "index + Nc". For example, if pos was 2.6 and count was 9, the index of the last character of the match would be 2.6+9c

    With that, and assuming you've already configured a tag named "search" (eg: text.tag_configure("search", background="green")), you can add this tag to the start and end of the match like this:

    text.tag_add("search", pos, "%s + %sc" (pos, countVar.get()))
    

    To highlight all matches, just put the search command in a loop, and adjust the starting position to be one character past the end of the previous match.

提交回复
热议问题