2016-01-22 65 views
1

我有一个很长的文本,我想通过给定的偏移量来突出显示一些跨度。 我如何用Tkinter实现这一目标?Python 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]跨度突出?

+0

您可以用'text.add_tag()' - http://effbot.org/tkinterbook/text.html – furas

回答

2

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

可以使用形式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)