Answer the question
In order to leave comments, you need to log in
Is it possible to highlight some words in Text? If so, how?
Is it possible to highlight some words in Text? Let's say there is a gui program in python and tkinter. And whenever the user writes "Hi", that word is highlighted in yellow. That is, all "Hello" in the text should be highlighted in yellow.
I was able to figure out how to do a permanent check for this:
1.
def checkSyntax():
#тут будет находиться проверка и выполнение
checkSyntax() # а это будет находиться перед root.mainloop()
Answer the question
In order to leave comments, you need to log in
Here, for example, is a simple example of highlighting with color:
def __create_problem_description_frame(self):
# здесь создаем сам виджет - self.problem_description_body
# self - это tk.Frame
# непосредственно вся логика
def f1(_event):
# ищем выделенный текст, но никак его не проверяем - одна буква или слово - без разницы
if self.problem_description_body.tag_ranges(tk.SEL):
print('SELECTED Text is %r' % self.problem_description_body.get(tk.SEL_FIRST, tk.SEL_LAST))
else:
print('NO Selected Text')
return
# в тексте ищем точные совпадения
pattern = str(self.problem_description_body.get(tk.SEL_FIRST, tk.SEL_LAST))
start = self.problem_description_body.index("1.0")
end = self.problem_description_body.index("end")
self.problem_description_body.mark_set("matchStart", start)
self.problem_description_body.mark_set("matchEnd", start)
self.problem_description_body.mark_set("searchLimit", end)
# как будем выделять - название тэга и желтый фон
self.problem_description_body.tag_configure("yellow", background="#ffff99")
# погнали искать все совпадения
count = tk.IntVar()
while True:
# непосредственно сам поиск
index = self.problem_description_body.search(
pattern, "matchEnd", "searchLimit", count=count, regexp=True)
if index == "":
break
if count.get() == 0:
break
# и, наконец, выделение найденного фрагмента текста тэгом с именем yellow
self.problem_description_body.mark_set("matchStart", index)
self.problem_description_body.mark_set("matchEnd", "%s+%sc" % (index, count.get()))
self.problem_description_body.tag_add("yellow", "matchStart", "matchEnd")
# биндим срабатывание на отпускание кнопки мыши
self.problem_description_body.bind('<ButtonRelease-1>', f1)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question