Tkinter 文本小部件 tag_add 第二次不起作用

Tkinter Text widget tag_add does not work second time

我正在编写我过去 20 年来的第一个 python 应用程序。我对 Tkinter 文本小部件的 tag_add() 函数有疑问。添加标签第一次有效,但第二次无效。我检查了 tag_names() 是否在取消选中 "Highlight Errors" 复选按钮时删除了我的标签。它被删除了。它甚至在再次检查复选按钮时重新添加,但第二次尝试时文本没有着色。

有人知道吗? 作为多年来的第一个 python 代码,您对我实现和构建它的方式有反馈吗? (抱歉无法摆脱 CamelCase)

提前致谢 SLi

from Tkinter import Tk, BOTH, END, N, W, S, TOP, BOTTOM, INSERT, LEFT, RIGHT, SUNKEN, RAISED, X, Y, PanedWindow, Frame, LabelFrame, Scrollbar, Checkbutton, Entry, Button, Label, Text, Menu, IntVar
from ScrolledText import ScrolledText


class Application(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.initializeUiVariables()
        self.doWindowSetup()
        self.createWidgets()
        self.doColorSetup()


    def doWindowSetup(self):
        self.parent.title('PACE Client Log Viewer')
        self.screenWidth = self.parent.winfo_screenwidth()
        self.screenHeight = self.parent.winfo_screenheight()
        desiredWindowWidth = (self.screenWidth * 1.0)
        desiredWindowHeight = (self.screenHeight * 1.0)
        x = (self.screenWidth / 2) - (desiredWindowWidth / 2)
        y = (self.screenHeight / 2) - (desiredWindowHeight / 2)
        self.parent.geometry('%dx%d+%d+%d' % (desiredWindowWidth, desiredWindowHeight, x, y))


    def initializeUiVariables(self):
        self.fontSize = 12
        self.highlightErrors = IntVar()



    def createWidgets(self):
        panedWindow = PanedWindow(sashrelief=RAISED)
        panedWindow.pack(fill=BOTH, expand=1)

        self.wText = ScrolledText(panedWindow)
        self.wText.config(font=("consolas", self.fontSize))
        self.wText.pack(side=LEFT, fill=BOTH, expand=True)
        panedWindow.add(self.wText, minsize=(self.screenWidth * 0.75))
        self.wText.insert(END, "2018-09-28 11:15:03 GMT - my.app.id (ERROR): Class:CertChecker:error: No certificate loaded.  Load certificate before continuing.\n2018-09-28 11:15:07 GMT - my.app.id (INFO): Class:PerformInitialization: begin - version 0.3.10")

        frameToolbar = Frame(panedWindow, padx=10)
        frameToolbar.pack(side=LEFT, fill=BOTH, expand=True)
        panedWindow.add(frameToolbar)

        # Highlight Options
        frameHighlightOptions = LabelFrame(frameToolbar, text="Highlight", padx=5, pady=5)
        frameHighlightOptions.pack(side=TOP, fill=BOTH)
        cbErrors = Checkbutton(frameHighlightOptions, text="Errors", anchor=W, padx=5, justify=LEFT, variable=self.highlightErrors, command=self.onHighlightErrors)
        cbErrors.pack(side=TOP, fill=X)

    def doColorSetup(self):
        self.wText.tag_config("highlightError", background="#EE2C2C", foreground="#FFFFFF") # red


    def onHighlightErrors(self):
        if self.highlightErrors.get() == 0:
            self.wText.tag_delete("highlightError")
        else:
            self.highlightRow("error", "highlightError")


    def highlightRow(self, pattern, tag):
        self.highlightPattern(pattern, tag, True)


    def highlightPattern(self, pattern, tag, highlightRow=False):
        start = self.wText.index("1.0")
        end = self.wText.index(END)
        self.wText.mark_set("matchStart", start)
        self.wText.mark_set("matchEnd", start)
        self.wText.mark_set("searchLimit", end)

        count = IntVar()
        while True:
            index = self.wText.search(pattern, "matchEnd","searchLimit", count=count, regexp=True, nocase=True)
            if index == "": break
            if count.get() == 0: break # degenerate pattern which matches zero-length strings
            if highlightRow:
                row, col = index.split('.')
                self.wText.mark_set("matchStart", "%s.%s" % (int(row), 0))
            else:
                self.wText.mark_set("matchStart", index)

            if highlightRow:
                lineEndIndex = self.wText.search("\n", index, "searchLimit", count=count, regexp=False, nocase=False)
                row, col = lineEndIndex.split('.')
                self.wText.mark_set("matchEnd", lineEndIndex)
            else:
                self.wText.mark_set("matchEnd", "%s+%sc" % (index, count.get()))
            self.wText.tag_add(tag, "matchStart", "matchEnd")


def main():
    root = Tk()
    ex = Application(root)
    root.mainloop()


if __name__ == '__main__':
    main() 

删除标签时,您会销毁与该标签关联的所有信息。下次添加标签时,它没有颜色与之关联,因此您看不到标签。

与其删除标签,不如将其从文本中删除。

替换为:

self.wText.tag_delete("highlightError")

...有了这个:

self.wText.tag_remove("highlightError", "1.0", "end")