我不知道的方式来指定文本标签的高亮颜色。
我看到两种方法可以解决您的问题,第一种方法是给"sel"
标记优先于oddLine
标记,因为pointed by Bryan。文本标签按照它们的创建顺序排序(最后创建在其他上面)。默认的"sel"
标签是使用该小部件创建的,因此低于之后添加的标签。
第二种方法是计算标签和"sel"
之间的交集以提供自定义样式。以下是实现此行为的代码片段。
import Tkinter as tk
t = tk.Text()
t.pack()
t.insert(tk.END, "Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
t.tag_config("foo", background="yellow", foreground="red")
t.tag_add("foo", "1.6", "1.11")
t.tag_add("foo", "1.28", "1.39")
t.tag_config("sel_intersection", background="orange")
def sel_manager(event):
t = event.widget
tag_remove_all (t, "sel_intersection")
f = map(TextIndex, t.tag_ranges("foo"))
s = map(TextIndex, t.tag_ranges("sel"))
if (len(s) == 0):
return
for f_start, f_end in zip(f[::2],f[1::2]):
t.tag_add("sel_intersection", max(s[0],f_start), min(s[1], f_end))
def tag_remove_all(widget, tag_name):
ranges = map(str, t.tag_ranges(tag_name))
for s, e in zip(ranges[::2], ranges[1::2]):
widget.tag_remove(tag_name, s, e)
class TextIndex:
'''needed for proper index comparison, ie "1.5" < "1.10"
'''
def __init__(self, textindex):
self._str = str(textindex)
self._l , self._c = map(int, self._str.split('.'))
def __cmp__(self, other):
cmp_l = cmp(self._l, other._l)
if cmp_l !=0:
return cmp_l
else:
return cmp(self._c, other._c)
def __str__(self):
return self._str
t.bind("<<Selection>>", sel_manager)
t.mainloop()
我不明白这个问题。如果你有一个灰色的背景,用户选择它,你想继续看到灰色背景,或者你期望看到高光背景?无论原始颜色如何,大多数编辑都显示相同的高光颜色,因此您始终可以知道所选内容。 –
@BryanOakley看我的编辑。 – Dean