在您调用的示例代码中
iter.backward_chars
在里面
TextBuffer.text_inserted
但你从来没用过它!,因此我制作了一个示例脚本,向您展示所需的行为并阐明:
import gtk
import pango
class TextBuffer(gtk.TextBuffer):
def __init__(self):
gtk.TextBuffer.__init__(self)
self.connect_after('insert-text', self.text_inserted)
# A list to hold our active tags
self.tags_on = []
# Our Bold tag.
self.tag_bold = self.create_tag("bold", weight=pango.WEIGHT_BOLD)
def get_iter_position(self):
return self.get_iter_at_mark(self.get_insert())
def make_bold(self):
''' add "bold" to our active tags list '''
if 'bold' in self.tags_on:
del self.tags_on[self.tags_on.index('bold')]
else:
self.tags_on.append('bold')
def text_inserted(self, buffer, iter, text, length):
# A text was inserted in the buffer. If there are ny tags in self.tags_on, apply them
if self.tags_on:
# This sets the iter back N characters
iter.backward_chars(length)
# And this applies tag from iter to end of buffer
self.apply_tag_by_name('bold', self.get_iter_position(), iter)
def main():
window = gtk.Window()
window.connect('destroy', lambda _: gtk.main_quit())
window.resize(300, 300)
tb = TextBuffer()
tv = gtk.TextView(buffer=tb)
accel = gtk.AccelGroup()
accel.connect_group(gtk.keysyms.b,
gtk.gdk.CONTROL_MASK,gtk.ACCEL_LOCKED,
lambda a,b,c,d: tb.make_bold())
window.add_accel_group(accel)
window.add(tv)
window.show_all()
gtk.main()
if __name__ == '__main__':
main()