我不知道的方式來指定文本標籤的高亮顏色。
我看到兩種方法可以解決您的問題,第一種方法是給"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