I have an app that I'm writing in python using gtk and I want it to automatically close parenthesis' and place the cursor between them The problem is I'm randomly getting the following error and having the program crash:
./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 pos开发者_如何学Pythonition 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
The code around that area is this:
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))
Can anyone tell me how to fix this error? I can't find any other fmethods to place the cursor at that particular between the parenthesis'
The insert_at_cursor
call invalidates the iterator passed in to your function. When you refer back to that iterator on the last line, GTK+ shows a warning. This behaviour is explained in the GTK+ Text Widget Overview.
Fixing this is a matter of not re-using the iterator, for example:
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)
(Disclaimer: I haven't used the GTK+ text widget in a long time. There's probably an easier / more elegant way to do the same thing, but this one does the job.)
精彩评论