Gtk-Python : Is it possible to print a window content and how to do this?

喜夏-厌秋 提交于 2019-12-23 06:04:36

问题


I have a Gtk.Window which contains a Gtk.Grid and Gtk.Labels. I would like to print all of what is displayed on this window. Is it possible to do this and how?

I've searched for tutorials but only found one to print pdf files.

Here is my print function :

def on_print(self, widget):
    print("*** Print ***")
    print_op = Gtk.PrintOperation()
    print_op.set_n_pages(1)
    print_op.connect("draw_page", self.print_window)
    res = print_op.run(Gtk.PrintOperationAction.PRINT_DIALOG, None)

def print_window(self):

Could you tell me what should I code in the "print_window" callback function, please?

Thank you in advance.


回答1:


Ok, so I have reworked the example I linked in my comment. This should only grab the box inside the window.

from gi.repository import Gtk, Gdk
import cairo
import sys


class MyWindow(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self, title="Welcome to GNOME")
        self.set_default_size(200, 100)
        self.image_file = image_file="/home/house/window.png"
        self.vbox = Gtk.VBox()
        self.add(self.vbox)
        label = Gtk.Label()
        label.set_text("Hello GNOME!")
        self.vbox.pack_start(label, True, True, 0)
        self.button = Gtk.Button("ScreenshotMe!")
        self.button.connect("clicked", self.on_save_image)
        self.vbox.pack_start(self.button, False, False, 0)
        self.show_all()
        self.connect("destroy", Gtk.main_quit)

    def on_save_image(self, button):
        """
        Get the surface of the current window and save it as a png
        """
        window = self.get_window()
        width, height = self.vbox.get_allocated_width(), \
                        self.vbox.get_allocated_height()
        surface = Gdk.Window.create_similar_surface(window,
                                                    cairo.CONTENT_COLOR,
                                                    width, height)
        cairo_context = cairo.Context(surface)
        Gdk.cairo_set_source_window(cairo_context, window, 0, 0)
        cairo_context.paint()
        surface.write_to_png(self.image_file)

def main():
    app = MyWindow()
    Gtk.main()

if __name__ == "__main__":
    sys.exit(main())


来源:https://stackoverflow.com/questions/53646008/gtk-python-is-it-possible-to-print-a-window-content-and-how-to-do-this

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!