该笔记将记录:在 GTK+ 3 中,如何使用 Pixbuf 在 TextView 中插入图片
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk
from gi.repository.GdkPixbuf import Pixbuf
import gi.repository.GdkPixbuf
class PluginInsertedObjectAnchor(Gtk.TextChildAnchor):
def create_widget(self):
return Gtk.Image.new_from_file("/usr/local/share/icons/d3rm/24x24-010editor.png")
def dump(self, builder):
attrib, data = self.objecttype.data_from_model(self.objectmodel)
builder.start(OBJECT, dict(attrib)) # dict() because ElementTree doesn't like ConfigDict
if data is not None:
builder.data(data)
builder.end(OBJECT)
class EditWindow(Gtk.Window):
def __init__(self):
# 创建 Window 控件
Gtk.Window.__init__(self)
self.set_default_size(200, 200)
# 创建 TextView 控件
textview = Gtk.TextView()
textbuffer = textview.get_buffer()
# 插入位置
iter = textbuffer.get_iter_at_mark(textbuffer.get_insert())
# 方法一、通过 Pixbuf 将图片插入 TextView 的 TextBuffer 中
pixbuf = Pixbuf.new_from_file("/usr/local/share/icons/d3rm/24x24-010editor.png")
textbuffer.insert_pixbuf(iter, pixbuf)
# 方法二、通过 Anchor 插入
anchor = textbuffer.create_child_anchor(iter)
image = Gtk.Image.new_from_file("/usr/local/share/icons/d3rm/24x24-010editor.png")
textview.add_child_at_anchor(image, anchor)
# 方法三、自定义 Anchor 对象
anchor = PluginInsertedObjectAnchor() # 自定义 Anchor 对象
textbuffer.insert_child_anchor(iter, anchor) # 将 Anchor 添加到 TextBuffer 中
textview.add_child_at_anchor(anchor.create_widget(), anchor) # 向 Anchor 中添加控件
# 将 TextView 加入 Window 中
self.add(textview)
win = EditWindow()
win.connect("destroy", Gtk.main_quit)
win.show_all()
Gtk.main()
注意事项:由于篇幅原因,我们将三种示例(方法一、方法二、方法三)放在一起。但是,它们三个是相互独立的,可单独使用;
参考文献
8.6. Inserting Child Widgets
13.3. Text Buffers
17. Multiline Text Editor — Python GTK+ 3 Tutorial 3.4 documentation
Gtk.Image – Classes – Gtk 3.0
Gtk.TextBuffer – Classes – Gtk 3.0
Gtk.TextBuffer · Python GTK+ 3 API
Gtk.TextIter · Python GTK+ 3 API
Gtk.TextView – Classes – Gtk 3.0
Gtk.TextView · Python GTK+ 3 API
How to get text buffer from file and loading into TextView using python and Gtk+3 – Ask Ubuntu