获取屏幕像素颜色linux python3

时间:2014-12-10 08:04:25

标签: python linux gtk linuxmint

我在python 2.7中有一个工作程序,我试图转换为python 3.3。

工作版本是:

#!/usr/bin/python2
import gtk.gdk
import sys

def PixelAt(x, y):
  w = gtk.gdk.get_default_root_window()
  pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, 1, 1)
  cm = w.get_colormap()
  pb = pb.get_from_drawable(w, cm, x, y, 0, 0, 1, 1)
  return pb.pixel_array[0][0]

print(PixelAt(int(sys.argv[1]), int(sys.argv[2])))

部分转换的是:

#!/usr/bin/python3
from gi.repository import Gtk, Gdk, GdkPixbuf
import sys

def PixelAt(x, y):
  w = Gdk.get_default_root_window()
  pb = GdkPixbuf.Pixbuf.new(GdkPixbuf.Colorspace.RGB, False, 8, 1, 1)
  cm = w.get_colormap()                              # What goes here?
  pb = pb.get_from_drawable(w, cm, x, y, 0, 0, 1, 1) # What goes here?
  return pb.pixel_array[0][0]

print(PixelAt(int(sys.argv[1]), int(sys.argv[2])))

完成转换需要什么?

[编辑]

感谢@jku,这是我完整的python3颜色选择器:

#!/usr/bin/python3
# Print RGB color values of screen pixel at location x, y
from gi.repository import Gdk
import sys

def PixelAt(x, y):
  w = Gdk.get_default_root_window()
  pb = Gdk.pixbuf_get_from_window(w, x, y, 1, 1)
  return pb.get_pixels()

print(tuple(PixelAt(int(sys.argv[1]), int(sys.argv[2]))))

[END-EDIT]

1 个答案:

答案 0 :(得分:3)

w = Gdk.get_default_root_window()
pb = Gdk.pixbuf_get_from_window(w, x, y, 1 ,1)

应该这样做。请注意,pixbuf_get_from_window()可以像您使用的Gdk2函数一样返回None:在使用之前必须检查返回值。