Created
August 31, 2019 19:40
-
-
Save stefanthaler/7f5541d45240e567cea6abcdc50c815e to your computer and use it in GitHub Desktop.
A small example for python-xlib that works of events in a semi-blocking way using select.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python3 | |
import sys | |
import os | |
from Xlib import X, display, Xutil | |
import select | |
# http://python-xlib.sourceforge.net/doc/html/python-xlib_11.html | |
# Application window (only one) | |
class Window(object): | |
def __init__(self): | |
print("Runs until escape is pressed.") | |
self.d = display.Display() | |
s = self.d.screen() | |
self.s = s | |
self.window = s.root.create_window( | |
0, 0, s.width_in_pixels, s.height_in_pixels, | |
2, s.root_depth, | |
X.InputOutput, X.CopyFromParent, | |
background_pixel = s.white_pixel, | |
event_mask = (X.KeyPressMask | X.KeyReleaseMask), | |
colormap = X.CopyFromParent, | |
) | |
self.gc = self.window.create_gc( | |
foreground = s.black_pixel, | |
background = s.white_pixel, | |
) | |
self.WM_DELETE_WINDOW = self.d.intern_atom('WM_DELETE_WINDOW') | |
self.window.map() # show window | |
# Main loop, handling events | |
def loop(self): | |
self.loop_cond = True | |
timeout=5 | |
while self.loop_cond: | |
# handle all available events | |
i = self.d.pending_events() | |
while i > 0: | |
event = self.d.next_event() | |
self.handle_event(event) | |
i = i - 1 | |
# Wait for display to send something, or a timeout of one second | |
readable, w, e = select.select([self.d], [], [], timeout) | |
# if no files are ready to be read, it's an timeout | |
if not readable: | |
self.handle_timeout() | |
def handle_timeout(self): | |
print("Timeout") | |
def handle_event(self, e): | |
if e.type == X.KeyRelease or e.type == X.KeyPress: | |
keycode = e.detail | |
print(keycode+" was pressed/released") | |
if (keycode==9): | |
self.loop_cond=False | |
if __name__ == "__main__": | |
window = Window().loop() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment