2016-01-22 74 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)