我有这个python代码,它截取x屏幕截图。
#!/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'对象没有使用sz = w.get_geometry()而不是get_size属性'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”属性? 再次感谢!
答案 0 :(得分:2)
也许你想要 get_width()和 get_height()。
根据他们的文档 get_size()已弃用:https://developer.gnome.org/gdk/stable/gdk-Drawing-Primitives.html#gdk-drawable-get-size
答案 1 :(得分:2)
我知道这个答案迟到了,但迟到总比没有好。
Gdk3 + 实际上简化了从Pixbuf
检索GdkWindow
的过程。因此,您的代码应如下所示:
#!/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."