python - gtk 文本 itters 的问题

标签 python gtk pygtk gtk-textbuffer

我有一个使用 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))

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

最佳答案

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+ 文本小部件了。可能有一种更简单/更优雅的方法来完成同样的事情,但这个可以完成这项工作。)

关于python - gtk 文本 itters 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4928308/

相关文章:

python - 循环直到出现完全可靠的异常

python - "Python 3.9"和 "Python 3.9 (venv)"解释器之间有什么区别?

python - Python 中高效的逐元素函数计算

c - 如何将字体设置为用户使用字体选择器选择的字体?

python - Pygtk 入口占位符

python - 如何将文本文件读入文本框?

python - 如何在 python 中 < n^2 时间内查找任意大小列表列表的副本?

自定义 GtkComboBoxText 的完成

c++ - GtkTreeView 中出现奇怪的符号

gtk - 如何在开罗表面上绘制任何 GTK 小部件