2011-02-09 94 views
11

我想保存一個GTK窗口的外觀,以及它包含的所有按鈕和其他小部件到PNG或PDF文件。開羅支持在這些表面上繪圖。 我能以某種方式請求一個GTK小部件在開羅表面繪製自己嗎? 代碼示例將非常感謝,因爲我是GTK和開羅的新手。 Python是我選擇的語言。如何在開羅表面上繪製任何GTK小部件

回答

10

在C語言中,你可以把你的按鈕和小部件在使用GtkOffscreenWindowgtk_widget_reparent()然後用gtk_offscreen_window_get_pixbuf()以使其到GdkPixbuf,然後你就可以保存到一個文件中。對不起,我沒有任何Python代碼,但我不認爲PyGTK中的屏幕外窗口可用。

10

ptomato說什麼。如果您需要在屏幕外執行此操作,請使用Gtk.OffscreenWindow,否則只需獲取Gdk窗口和窗口小部件的分配即可將其剪下。這是一個可用於獲取任何窗口小部件快照的片段。如下面的代碼所示,您還可以使用Gtk.Widget.draw()方法在Cairo上下文中呈現它。

from gi.repository import Gtk 
import cairo 

WINDOW_WIDTH, WINDOW_HEIGHT = 400, 300 

window = Gtk.OffscreenWindow() 
window.set_default_size(WINDOW_WIDTH, WINDOW_HEIGHT) 
window.show() 

canvas = Gtk.HBox() 
window.add(canvas) 
canvas.show() 

button = Gtk.Button("Hello World!") 
canvas.add(button) 
button.show() 

# this is needed, otherwise the screenshot is black: 
while Gtk.events_pending(): 
    Gtk.main_iteration() 

surf = cairo.ImageSurface(cairo.FORMAT_ARGB32, 
          WINDOW_WIDTH, WINDOW_HEIGHT) 

cr = cairo.Context(surf) 
canvas.draw(cr) 
surf.write_to_png('test.png') 

可以暫時重新設置父級的窗口小部件(如ptomato說的)這個Gtk.OffscreenWindow,爲了使快照。

original_parent = canvas.get_parent() 
canvas.reparent(offscreen_window) 

# do snapshot 

canvas.reparent(original_parent)