python - 如何突出显示 tkinter.Text 中的特定单词?
问题描述
这不是这个问题的副本:How to highlight text in a tkinter Text widget。这更像是一个延续。从这个问题,我得到了这个代码:
class CustomText(tk.Text):
'''A text widget with a new method, highlight_pattern()
example:
text = CustomText()
text.tag_configure("red", foreground="#ff0000")
text.highlight_pattern("this should be red", "red")
The highlight_pattern method is a simplified python
version of the tcl code at http://wiki.tcl.tk/3246
'''
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 according to Tcl's regular expression syntax.
'''
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
if count.get() == 0: break # degenerate pattern which matches zero-length strings
self.mark_set("matchStart", index)
self.mark_set("matchEnd", "%s+%sc" % (index, count.get()))
self.tag_add(tag, "matchStart", "matchEnd")
此代码运行良好,但我遇到了问题。我实际上想在我的 python 编辑器的颜色编码中使用这个突出显示功能。问题是,每当我使用它时,我都需要它来为单词着色,但它会在找到它的任何地方为字母着色,即使换句话说。(例如:当我尝试突出显示单词“on”时,单词“one”中的“on”也会着色)任何人都可以为我修改此代码,所以它只会着色单词。
解决方案
所以我找到了这篇文章:使用搜索方法在文本小部件中搜索整个单词,这段代码似乎运行良好:
textArea.highlight_pattern("\\y" + word + "\\y", "tag", regexp=True)
推荐阅读
- regex - Visual Studio Code:正则表达式以开头但不以结尾
- qt - 如何强制 Qt 更新/修复隐藏的 QWidget 以进行视频捕获?
- kotlin - 应将 Lambda 参数移出括号
- android - RecyclerView last Item 没有完整显示item,因为上面的TabLayout
- android - 从Activity中获取fragment的TextView数据
- javascript - Sidebar DOM 与 Navbar 重叠,将其从 DOM 中移除
- javascript - Chrome 扩展程序:创建了多个页面
- node.js - 我想使用 Pond.js 但不知道如何要求它
- matlab - Matlab中矩阵中每10个数字的平均值
- exe - 在用 launch4j 包装的 Firefox 上阻止 .exe 下载