如何在文本小部件中搜索整个单词?

问题描述

我正在使用 Python 和 tkinter 开发 Python 文本编辑器。但是我在更改文本小部件的字体颜色时遇到了一些问题。
我刚开始写。
到那时才 5 分钟。

这里是 editor.py

##imports
from tkinter import Tk,Text,BOTH,font
from font import fontify

##When the text gets edited
def Keyboardpress(key):
    editarea_text = editArea.get("1.0","end")
    ##Calling the fontify function for doing some chill!
    fontify(editArea,editarea_text)

##Creating Window
editor = Tk()

##resizing editor
editor.geometry("400x400")

##creating a font
myFont = font.Font(family='Courier',size = 24,weight = "normal")

##Here goes the ui
editArea = Text(editor,bg="#333",fg="#eee",height = 400,width = 400,font = myFont)
editArea.bind('<key>',print())
editArea.pack(fill = BOTH)

##binding Button press with editor
editor.bind( '<Key>',lambda i : Keyboardpress(i))

##Excecuting Window
editor.mainloop()

**这是font.py**
keywords = ["False","await","else","import","pass","None","break","except","in","raise","True","class","def"]#and so on

def fontify(self,self_text):
    self.tag_remove('keyword','1.0',"end")

    for word in keywords:
        idx = '1.0'
        while idx:
            idx = self.search(word,idx,nocase=0,stopindex="end")
            if idx:
                lastidx = '%s+%dc' % (idx,len(word))
                self.tag_add('keyword',lastidx)
                idx = lastidx

    self.tag_config('keyword',foreground='deeppink')

running This Gives me desired output

But how to remove these undesired colored ones

解决方法

这对我有帮助
idx = self.search(word,idx,forwards=0,backwards=0,stopindex="end")

argument forwards 表示在搜索中接受字符向前。
backwards 参数正好相反。
让它们成为假对我有帮助
谢谢