Reputation: 61
I am new to tkinter and I want to implement highlighting and de-highlighting of text using tkinter tags. I tried tag_remove() method but thats erring in my case so I thought to implement highlighting and de-highlighting in this way. I want the text to highlight when I press 'a'on the keyboard, dehighlight when I press 'x', and again highlight when I press 'a'. Is there any way to set the priorities of tags so that my goal is achieved? Any help would be highly appreciated. Thanks in advance!
from tkinter import *
import tkinter as tk
from tkinter import Frame, Menu
from tkinter import ttk
class AnnotationTool(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
self.tagA='INGREDIENT'
self.keyA='a'
self.results_field = Text(self)
self.results_field.config(height=20,spacing1=5,wrap='word',undo=True)
self.results_field.grid(pady=10,column=3,row=3,padx=10,rowspan=12)
self.results_field.insert('insert','abc def ghi')
self.results_field.focus()
self.results_field.tag_configure(self.tagA, background="yellow")
self.results_field.tag_configure('hide', background="white")
self.results_field.bind(self.keyA, self.onKeyPressA)
self.results_field.bind('x', self.onKeyPressX)
def onKeyPressA(self,event):
self.results_field.tag_add(self.tagA, 'sel.first', 'sel.last')
return "break"
def onKeyPressX(self,event):
self.results_field.tag_add('hide','sel.first', 'sel.last')
return "break"
class App(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self._frame = None
self.switch_frame(AnnotationTool)
self.title('App')
def switch_frame(self, frame_class):
new_frame = frame_class(self)
if self._frame is not None:
self._frame.pack_forget()
self._frame = new_frame
self._frame.pack()
def main():
app=App()
app.geometry("1300x1000")
app.mainloop()
if __name__ == '__main__':
main()
Upvotes: 0
Views: 51
Reputation: 385900
tag_remove
is the proper way to remove the highlighting. It's not clear if you want to remove only the highlighting at the current position or everywhere. Assuming you only want the highlighting after the insertion point, you can do something like this:
tag_range = self.results_field.tag_nextrange(self.tagA, "insert")
if tag_range:
self.results_field.tag_remove(self.tagA, *tag_range)
If you don't want to do that and instead want to stack another tag on top, you can change the priority with tag_raise
. The following moves the "hide" tag above self.tagA
:
self.results_field.tag_raise("hide", self.tagA)
Upvotes: 1