【问题标题】:Python Tkinter change Text background of some textual spansPython Tkinter改变一些文本跨度的文本背景
【发布时间】:2016-01-22 21:41:21
【问题描述】:

我有一个很长的文本,我想通过给定的偏移量突出显示一些跨度。 如何使用 Tkinter 实现这一目标?

为了更具体,请考虑以下几点:

from Tkinter import *
example = """Contrary to popular belief, \n\n Lorem Ipsum is not simply random text. It has roots in a piece of \n\n classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.
"""
offsets = [[10,20], [100,112]]

root = Tk()

text = Text(root)
text.insert(INSERT, example)
text.pack()
root.mainloop()

如何突出显示与example[10:20]example[100:112] 对应的跨度?

【问题讨论】:

标签: python tkinter


【解决方案1】:

您可以定义一个标签,并将该标签应用于一系列字符。

您可以使用1.0 + <offset>c 形式的索引,它将计算一个新索引,即从索引 1.0 开始的 个字符。

例如:

text.tag_configure("highlight", background="yellow")
for start, end in offsets:
    text.tag_add("highlight", "1.0 + %sc"%start, "1.0 + %sc"%end)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多