如何从 Gtk.DrawingArea 获取像素?

How to get pixels from Gtk.DrawingArea?

我正在写一个简单的绘画类应用程序:

#!/usr/bin/env python3

from gi.repository import Gtk


class Application(Gtk.Window):

    def __init__(self):
        super().__init__(Gtk.WindowType.TOPLEVEL, title='paint')
        self.connect('destroy', self.__on_destroy)
        vbox = Gtk.VBox()
        drawing_area = Gtk.DrawingArea()
        drawing_area.conenct('draw', self.__on_draw)
        vbox.pack_start(drawing_area, True, True, 2)
        self.add(vbox)
        self.show_all()

    def __on_draw(self, widget, g):
        g.set_source_rgb(200, 0, 0)
        g.move_to(16, 0)
        g.line_to(16, 32)
        g.stroke()

    def save_to_file(self, filename):
        # How to get pixels from drawing_area?
        pass

    def __on_destroy(self, e):
        Gtk.main_quit()

app = Application()
Gtk.main()

现在我想保存用户绘图。如何访问 Gtk.DrawingArea 小部件内的像素?

引自以下SO link

Gtk.DrawingArea derives from Gtk.Window.Hence you can use Gdk.pixbuf_get_from_window() to get the contents of the drawing area into a GdkPixbuf.Pixbuf and then use the GdkPixbuf.Pixbuf.savev() function to write the pixbuf as an image on disk.

你可以按照link完成code.Also这个link也可以帮助你。