我有这个截取 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 Gdk
gtk.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”属性?再次感谢!