【问题标题】:Gtk-Python : Is it possible to print a window content and how to do this?Gtk-Python:是否可以打印窗口内容以及如何执行此操作?
【发布时间】:2018-12-06 06:51:40
【问题描述】:

我有一个 Gtk.Window,其中包含一个 Gtk.Grid 和 Gtk.Labels。 我想打印此窗口上显示的所有内容。是否有可能做到这一点以及如何做到这一点?

我已经搜索过教程,但只找到了一个打印 pdf 文件的教程。

这是我的打印功能:

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):

您能告诉我应该在“print_window”回调函数中编写什么代码吗?

提前谢谢你。

【问题讨论】:

  • 你好@theGtknerd。我已经尝试过您链接的解决方案,但它保存了所有窗口内容,包括窗口本身。我想只获得 Gtk.Grid 的图像,没有窗口框架(例如网格,但它可以是窗口包含的任何其他小部件)

标签: python printing gtk


【解决方案1】:

好的,所以我已经修改了我在评论中链接的示例。这应该只抓取窗口内的框。

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())

【讨论】:

  • 谢谢@theGtknerd。我试过这段代码。实际上,要打印的表面只包括 vbox 和按钮。这更好,但我只想打印 vbox。有没有办法只选择 vbox 小部件或选择具有 x、y、高度和宽度的表面?我检查了 Cairo 函数,发现有 gdk_cairo_draw_from_gl ()、gdk_cairo_rectangle () 和 gdk_cairo_region () 方法。但我不知道这些是否会起作用并且不知道如何使用它们。没有找到关于它的例子。
  • 至少,我在此页面上找到了一个使用 rectangle() 方法的简单示例:askubuntu.com/questions/220350/… 我会看看我能用它做什么。
  • 或者,您可以重新排列小部件并在 vbox 中添加另一个网格,然后只抓取网格区域。
猜你喜欢
  • 1970-01-01
  • 2015-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多