Alex Katarani
Alex Katarani

Reputation: 21

How can I unselect the selected area in the Tkinter text widget?

I'm writing a simple search engine for a text widget in Tkinter. when I write a number of identical words The button is supposed to find the next identical word but for some reason text.tag_delete('sel', '1.0', 'end') doesn't unselect previous selected words and keep them selected.


from tkinter import Text, Entry,Button,Tk, SEL_FIRST

_findLoc = []
def _resetFind(e):
    global _findLocs
    _findLocs = []

def find():
    global _findLocs
    word = entry.get()
    
    #######################################################
    text.tag_delete('sel','1.0','end')# Here is the Problem
    #######################################################
    
    if len(_findLoc)==0:
        location = text.search(word,'1.0')
    else:
        location = text.search(word,_findLoc[-1])    
    
    locationEnd = location.split('.')[0]+'.'+str(int(location.split('.')[1])+len(word))
    _findLoc.append(locationEnd)
    text.tag_add("sel", location,locationEnd)
    text.focus_force()


root = Tk()

text= Text(root)
entry = Entry(root)
button=Button(root,text='Find',command=find)
text.insert('insert','test test test')
entry.insert('inser','test')
text.pack()
entry.pack()
button.pack()

root.mainloop()

I need a way to unselect the selected area widout deleting and reinserting the text to the widget.

Upvotes: 0

Views: 236

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385980

You cannot delete the "sel" tag, it is special to tkinter. What you want to do instead is remove the tag with tag_remove rather than tag_delete.

Upvotes: 1

Related Questions