我正在尝试写一个程序,它将从Gtk.TextView中获取数据并为其分配标签。基本上是一个markdown格式化程序。但是每当我为意大利语添加 * * 集时,整个程序就会崩溃。
这是我的代码。它不是最好看的代码,因为我是在试验这个想法。
# Imports
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Pango
class MarkdownFormatter:
def __init__(self, textview):
self.textview = textview
self.text_buffer = self.textview.get_buffer()
self.text_buffer.connect('insert-text', self.on_key_insert)
self.tag_bold = self.text_buffer.create_tag('bold',weight=Pango.Weight.BOLD)
self.tag_italic = self.text_buffer.create_tag('italic',style=Pango.Style.ITALIC, )
self.tag_underline = self.text_buffer.create_tag('underline',underline=Pango.Underline.SINGLE)
self.bold= False
self.italic = False
self.italic_start_iter = Gtk.TextIter()
self.italic_end_iter = Gtk.TextIter()
self.underline = False
def on_key_insert(self, buffer, inter, text, iteg):
end= self.text_buffer.get_end_iter()
start= self.text_buffer.get_start_iter()
all_text = self.text_buffer.get_text(end, start, True)
self.text_buffer.remove_all_tags(start, end)
count = 0
self.italic = False
for d in all_text:
count+= 1
if '*' in d:
if self.italic == False:
self.italic = True
self.italic_start_iter.set_offset(count)
elif self.italic:
self.italic = False
self.italic_end_iter.set_offset(count)
self.text_buffer.apply_tag(self.tag_italic, self.italic_start_iter, self.italic_end_iter)
text = '''
*I is good.*
she is smart.
"Hi" he said.
'''
if __name__ == '__main__':
def quit(*args):
Gtk.main_quit()
window = Gtk.Window.new(Gtk.WindowType.TOPLEVEL)
window.set_title('Markdown formatter')
view = Gtk.TextView()
view.get_buffer().set_text(text)
formater = MarkdownFormatter(view)
window.set_default_size(600, 400)
window.add(view)
window.show_all()
window.connect('delete-event', quit)
Gtk.main()
运行该程序,然后当你尝试键入任何东西,它会崩溃(它只尝试格式化文本时,你键入。
1条答案
按热度按时间y1aodyip1#
我找到了答案。我不知道为什么,所以如果有人能知道为什么,我会很高兴。
基本上,如果你用
itername = buffer.get_iter_at_offset(count)
替换set_offset
(s),它会运行得很好。我唯一的猜测是,这与重用缓冲区有关,或者set_offset有问题。