为周围的文本添加标签:
tk.SEL_FIRST + '-6c', tk.SEL_FIRST # for \term{
tk.SEL_LAST, tk.SEL_LAST + '+1c' # for }
使用Text.tag_config(tag_name, background=...)设置颜色
在下面的例子中,我使用term作为标签名:
try:
import Tkinter as tk
except ImportError:
import tkinter as tk
class MyFrame(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
self.txt = tk.Text(self)
self.txt.pack()
self.txt.insert(0.0, 'hello\nworld')
self.btn = tk.Button(self, text='add_term', command=self.add_term)
self.btn.pack()
self.txt.tag_config('term', background='red')
def add_term(self):
self.txt.insert(tk.SEL_FIRST,'\\term{')
self.txt.insert(tk.SEL_LAST,'}' )
self.txt.tag_add('term', tk.SEL_FIRST + '-6c', tk.SEL_FIRST)
self.txt.tag_add('term', tk.SEL_LAST, tk.SEL_LAST + '+1c')
root = tk.Tk()
f = MyFrame(root)
f.pack()
root.mainloop()
更新
调用insert时可以指定标签名,而不是事后添加标签:
def add_term(self):
self.txt.insert(tk.SEL_FIRST, '\\term{', 'term')
self.txt.insert(tk.SEL_LAST, '}', 'term')