2

我有一个使用 gtk 在 python 中编写的应用程序,我希望它自动关闭括号'并将光标放在它们之间问题是我随机收到以下错误并且程序崩溃:

    ./mbc.py:266: GtkWarning: Invalid text buffer iterator: either the iterator is 
uninitialized, or the characters/pixbufs/widgets in the buffer have been modified since
 the iterator was created.
    You must use marks, character numbers, or line numbers to preserve a position across
 buffer modifications.
    You can apply tags and insert marks without invalidating your iterators,
    but any mutation that affects 'indexable' buffer contents (contents that can be 
referred to by character offset)
    will invalidate all outstanding iterators
      buff.place_cursor(buff.get_iter_at_line_offset(itter.get_line(),Iter.get_offset()-1))
    ./mbc.py:266: GtkWarning: gtktextbtree.c:4094: char offset off the end of the line
      buff.place_cursor(buff.get_iter_at_line_offset(itter.get_line(),Iter.get_offset()-1))

    Gtk-ERROR **: Char offset 568 is off the end of the line
    aborting...
    Aborted

该区域周围的代码是这样的:

def insert_text(self, buff, itter, text, length):
    if text == '(':
        buff.insert_at_cursor('()') 
        mark = buff.get_mark('insert')
        Iter = buff.get_iter_at_mark(mark)
        buff.place_cursor(buff.get_iter_at_line_offset(itter.get_line(),Iter.get_offset()-1))

谁能告诉我如何解决这个错误?我找不到任何其他 fmethods 将光标放在括号之间的那个特定位置

4

1 回答 1

2

insert_at_cursor调用使传递给您的函数的迭代器无效。当您返回最后一行的那个迭代器时,GTK+ 会显示一个警告。GTK+ Text Widget Overview中解释了这种行为。

解决这个问题是不重新使用迭代器,例如:

buff.insert_at_cursor(')')  # This invalidates existing iterators.
mark = buff.get_mark('insert')
iter = buff.get_iter_at_mark(mark)  # New iterator
iter.backward_cursor_positions(1)
buff.place_cursor(iter)

(免责声明:我已经很长时间没有使用 GTK+ 文本小部件了。可能有一种更简单/更优雅的方式来做同样的事情,但是这个可以完成工作。)

于 2011-02-08T06:09:49.573 回答