Search for words/letters in the text widget (tkinter)

后端 未结 2 632
孤城傲影
孤城傲影 2021-01-23 12:38

How would I go about adding a search function that searches for text in the text widget? * Search from user input

def openFile():
    global text
    artiststxt          


        
2条回答
  •  日久生厌
    2021-01-23 13:43

    Okay, I figured it out. Took some time but well worth it.

    First we make an entry box in the window and we bind it with the enter key and put a .get event

    searchent.bind("", get)

    When enter key is pressed, we go to def get(event):

    def get(event):
    global searchent 
    text.tag_remove('found', '1.0', END)
    s = searchent.get() # Grabs the text from the entry box
    if s:
        idx = '1.0'
        while 1:
            idx = text.search(s, idx, nocase=1, stopindex=END)
            if not idx: break
            lastidx = '%s+%dc' % (idx, len(s))
            text.tag_add('found', idx, lastidx)
            idx = lastidx
            text.see(idx)  # Once found, the scrollbar automatically scrolls to the text
        text.tag_config('found', foreground='red')
    searchent.focus_set()
    

提交回复
热议问题