Python find function selects one match per line

I am trying to make a simple text editor using python. I am now trying to make a find function. This is what I've got:

def Find():
    text = textArea.get('1.0', END+'-1c').lower()
    input = simpledialog.askstring("Find", "Enter text to find...").lower()
    startindex = []
    endindex = []
    lines = 0
    if input in text:
        text = textArea.get('1.0', END+'-1c').lower().splitlines()
        for var in text:
            character = text[lines].index(input)
            start = str(lines + 1) + '.' + str(character)
            startindex.append(start)
            end = str(lines + 1) + '.' + str(character + int(len(input)))
            endindex.append(end)
            textArea.tag_add('select', startindex[lines], endindex[lines])
            lines += 1

    textArea.tag_config('select', background = 'green')

This will succesfully highlight words that match the users input with a green background. But the problem is, that it only highlights the first match every line, as you can see here.

I want it to highlight all matches.

Full code here: https://pastebin.com/BkuXN5pk

1 answer

  • answered 2017-06-17 17:56 Ron Norris

    Recommend using the text widget's built-in search capability. Shown using python3.

    from tkinter import *
    
    root = Tk()
    textArea = Text(root)
    textArea.grid()
    textArea.tag_config('select', background = 'green')
    
    f = open('mouse.py', 'r')
    content = f.read()
    f.close()
    textArea.insert(END, content)
    
    def Find(input):
        start = 1.0
        length = len(input)
        while 1:
            pos = textArea.search(input, start, END)
            if not pos:
                break
            end_tag = pos + '+' + str(length) + 'c'
            textArea.tag_add('select', pos, end_tag)
            start = pos + '+1c'
    
    Find('display')
    root.mainloop()