Get screen pixel color linux python3

我与影子孤独终老i 提交于 2021-01-04 08:59:26

问题


I have a working program in python 2.7 that I am trying to convert to python 3.3.

The working version is:

#!/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])))

The partly converted one is:

#!/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])))

What do I need to finish converting?

[EDIT]

Thanks to @jku here is my complete python3 color picker:

#!/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:


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

that should do it. Note that pixbuf_get_from_window() can return None just like the Gdk2 function you used: you must check the return value before using it.



来源:https://stackoverflow.com/questions/27395968/get-screen-pixel-color-linux-python3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!