【问题标题】:How to highlight certain words in Text Tk()如何突出显示 Text Tk() 中的某些单词
【发布时间】:2019-06-04 03:47:07
【问题描述】:

我正在尝试在 Text Tk() 中给出可识别的句子。我想根据它们的标签用不同的颜色突出显示某些标记。我正在将模型结果部署到 GUI。模型输出文本文件格式如下:

# 1.0000
This B-LOC
is I-LOC
example I-LOC
of E-LOC
my O
data O
format O
. O
In O
this B-ORG
place E-ORG
, O
characters O
of O
my O
language O
is B-PNAME
applied E-PNAME
. O

And S-PNAME
help O
Me. O

这是代码示例。

if l_list[i] == "S-PNAME" or "B-PNAME" or "I-PNAME" or "E-PNAME":

    self.output.update()
    self.output.insert(END,s_list[i])
    self.output.config(foreground='red')                                   

elif l_list[i] == "S-ORG" or "B-ORG" or "I-ORG" or "E-ORG":              

    self.output.update()
    self.output.insert(END,s_list[i])
    self.output.config(foreground='pink') 

else:
    self.output.update()
    self.output.insert(END,s_list[i])

我想用红色的 P-NAME 标签、用粉红色的 LOC 标签等为标记着色......但是在我的输出中,所有句子都是红色的。

【问题讨论】:

  • # 1.0000 这个 B-LOC 是 I-LOC 示例 I-LOC 的 E-LOC 我的 O 数据 O 格式 O 。 O 在 O 这个 B-ORG 中 E-ORG , O 我的 O 语言 O 的 O 字符 O 是 B-PNAME 应用的 E-PNAME 。 O 和 S-PNAME 帮助 O 我。 O
  • 我已将您的文本格式化为一个块,如果这不是您想要的,请重新编辑。

标签: python tkinter text tk


【解决方案1】:

我假设您的 self.output 是文本小部件。目前您只是通过调用self.output.config(foreground=...) 来修改小部件中所有文本的前景。

要为不同的文本高亮颜色,需要为插入的文本设置tag,然后使用tag_config配置每个标签的颜色。

import tkinter as tk

root = tk.Tk()

text = tk.Text(root)
text.pack()

text.insert(tk.INSERT,"This is a red message\n","red")
text.insert(tk.INSERT,"This is a green message\n","green")
text.insert(tk.INSERT,"This is a blue message\n","blue")

text.tag_config("red", foreground="red")
text.tag_config("green", foreground="green", relief="sunken",borderwidth=2)
text.tag_config("blue", foreground="blue", underline=1)

root.mainloop()

【讨论】:

  • 谢谢。但它不起作用。如果 l_list[i] == "S-PNAME" or "B-PNAME" or "I-PNAME" or "E-PNAME": self.output.tag_configure('red',foreground='red') self.output .insert(END,s_list[i],'red') elif l_list[i] == "S-ORG" or "B-ORG" or "I-ORG" or "E-ORG": self.output.tag_configure ('pink',foreground='pink') self.output.insert(END,s_list[i],'pink')
  • “不起作用”没有描述问题。您在执行时收到了什么错误?
  • 输入测试文件格式类似于 CoNLL 数据格式。在文本输出中,我希望将此输入标记作为序列并突出显示某些标记。
  • 我发现所有标记都用红色突出显示。
  • 您不能只是将所有导入到Text 小部件的文本转储并期望自动标记所有关键字。请参阅this post,了解如何通过搜索标记关键字。
猜你喜欢
  • 1970-01-01
  • 2016-01-19
  • 2015-01-12
  • 2017-10-23
  • 2022-01-07
  • 2016-03-22
  • 2018-10-31
  • 2013-08-08
  • 1970-01-01
相关资源
最近更新 更多