我按照已经回答的问题here但由于某些原因无法使其正常工作。示例代码低于我尝试过以及我遇到问题的地方。
from Tkinter import *
import Tkinter as tk
root = Tk()
textbox = Text(root)
textbox.insert(INSERT, "Hello, world!\n")
textbox.insert(END, "i highlight you, you hightlight him, he highlights me...loop it")
textbox.pack(expand=1, fill=BOTH)
class CustomText(tk.Text):
def __init__(self, *args, **kwargs):
tk.Text.__init__(self, *args, **kwargs)
def highlight_pattern(self, pattern, tag, start="1.0", end="end",
regexp=False):
'''Apply the given tag to all text that matches the given pattern
If 'regexp' is set to True, pattern will be treated as a regular
expression.
'''
start = self.index(start)
end = self.index(end)
self.mark_set("matchStart", start)
self.mark_set("matchEnd", start)
self.mark_set("searchLimit", end)
count = tk.IntVar()
while True:
index = self.search(pattern, "matchEnd","searchLimit",
count=count, regexp=regexp)
if index == "": break
self.mark_set("matchStart", index)
self.mark_set("matchEnd", "%s+%sc" % (index, count.get()))
self.tag_add(tag, "matchStart", "matchEnd")
CustomText()
textbox.tag_configure("red", foreground="red")
textbox.highlight_pattern("loop it", "red")
root.mainloop()
我收到以下错误:
textbox.highlight_pattern("loop it", "red")
AttributeError: Text instance has no attribute 'highlight_pattern'
我想要的是什么:
我理解错误,但我不知道如何使用该链接中提到的类突出显示loop it
或textbox
中的任何文本。这听起来很简单,但我仍然无法弄清楚应该如何使用这个类。
答案 0 :(得分:1)
改变这个:
textbox = Text(root)
对此:
textbox = CustomText(root)
当然,您必须重新安排代码,以便在使用之前定义类。