Skip to content

Instantly share code, notes, and snippets.

@campaul
Created November 25, 2015 08:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save campaul/72546ae6cfc7075afa9e to your computer and use it in GitHub Desktop.
Save campaul/72546ae6cfc7075afa9e to your computer and use it in GitHub Desktop.
Samples a color from the screen and prints the hex value to the terminal.
# Samples a color from the screen and prints the hex value to the terminal.
# Usage: `python color_picker.py` and then click somewhere to sample.
from gi import require_version
require_version('Gdk', '3.0')
require_version('Gtk', '3.0')
from gi.repository import Gdk
from gi.repository import Gtk
import sys
def get_hex_color(window, x, y):
pixbuf = Gdk.pixbuf_get_from_window(window, x, y, 1, 1)
rgb = pixbuf.get_pixels()
return tuple(map(int, rgb))
def event_handler(event, window, _):
if event.type == Gdk.EventType.BUTTON_RELEASE:
# Strictly speaking this isn't necessary since the program is about to
# exit, but I've included it for the sake of completeness.
Gdk.pointer_ungrab(Gdk.CURRENT_TIME)
_, x, y = event.get_coords()
# Understanding this is left as an exercise for the reader.
print('#%02x%02x%02x' % get_hex_color(window, x, y))
sys.exit(0)
if __name__ == '__main__':
window = Gdk.get_default_root_window()
Gdk.event_handler_set(event_handler, window, None)
# This changes the cursor and makes it so clicks won't register on other
# windows and change focus.
Gdk.pointer_grab(
window,
False,
Gdk.EventMask.ALL_EVENTS_MASK,
None,
# Not the best cursor, but I needed something to differentiate from
# the system default.
Gdk.Cursor(Gdk.CursorType.CROSSHAIR),
Gdk.CURRENT_TIME,
)
# TODO: Should probably grab the keyboard too so the user can't alt-tab
# and get into an odd state.
Gtk.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment