5

我有这个截取 x 屏幕截图的 python 代码。

#!/usr/bin/python
import gtk.gdk

w = gtk.gdk.get_default_root_window()
sz = w.get_size()
print "The size of the window is %d x %d" % sz
pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,False,8,sz[0],sz[1])
pb = pb.get_from_drawable(w,w.get_colormap(),0,0,0,0,sz[0],sz[1])
if (pb != None):
    pb.save("screenshot.png","png")
    print "Screenshot saved to screenshot.png."
else:
    print "Unable to get the screenshot."

它可以工作,但我需要导入from gi.repository import Gdkgtk.gdk。我尝试了以下方法:

#!/usr/bin/python
from gi.repository import Gtk, Gdk, GdkPixbuf
from gi.repository.GdkPixbuf import Pixbuf

w = Gdk.get_default_root_window()
sz = w.get_size()
print "The size of the window is %d x %d" % sz
pb = Pixbuf(Gdk.COLORSPACE_RGB,False,8,sz[0],sz[1])
pb = pb.get_from_drawable(w,w.get_colormap(),0,0,0,0,sz[0],sz[1])
if (pb != None):
    pb.save("screenshot.png","png")
    print "Screenshot saved to screenshot.png."
else:
    print "Unable to get the screenshot."

但:

Traceback (most recent call last):
  File "./dsd", line 6, in <module>
    sz = w.get_size()
AttributeError: 'gtk.gdk.X11Window' object has no attribute 'get_size'

有没有办法为这个脚本完全使用 gi.repository ?谢谢

编辑:我解决了 AttributeError 的问题:'gtk.gdk.X11Window' 对象没有属性 'get_size' 使用 sz = w.get_geometry() 而不是 get_size。新代码:

#!/usr/bin/python
from gi.repository import Gtk, Gdk, GdkPixbuf 
from gi.repository.GdkPixbuf import Pixbuf

w = Gdk.get_default_root_window()
sz = w.get_geometry()
#print "The size of the window is %d x %d" % sz
pb = GdkPixbuf.Pixbuf.new(GdkPixbuf.Colorspace.RGB,False,8,sz[2],sz[3])
pb = pb.get_from_drawable(w,w.get_colormap(),0,0,0,0,sz[2],sz[3])
if (pb != None):
    pb.save("screenshot.png","png")
    print "Screenshot saved to screenshot.png."
else:
    print "Unable to get the screenshot."

但这段代码还有另一个问题:

Traceback (most recent call last):
  File "./dsd", line 9, in <module>
    pb = pb.get_from_drawable(w,w.get_colormap(),0,0,0,0,sz[2],sz[3])
AttributeError: 'Pixbuf' object has no attribute 'get_from_drawable'

如何使用 Pixbuf 的“get_from_drawable”属性?再次感谢!

4

2 回答 2

4

我知道这个答案来得有点晚,但迟到总比没有好。

Gdk3+实际上简化了PixbufGdkWindow. 因此,您的代码应如下所示:

#!/usr/bin/python
from gi.repository import Gdk, GdkPixbuf

w = Gdk.get_default_root_window()
sz = w.get_geometry()[2:4]
#print "The size of the window is %d x %d" % sz
pb = Gdk.pixbuf_get_from_window(w, 0, 0, sz[0], sz[1])
if (pb != None):
    pb.savev("screenshot.png","png", [], [])
    print "Screenshot saved to screenshot.png."
else:
    print "Unable to get the screenshot."
于 2016-06-11T22:14:48.147 回答
2

也许你想要get_width()get_height()

根据他们的文档,不推荐使用get_size()https ://developer.gnome.org/gdk/stable/gdk-Drawing-Primitives.html#gdk-drawable-get-size

于 2013-08-13T04:51:50.877 回答