[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

5.1 Getting Events

Events can be sent at any time, not necessarily when the client is ready to receive an event. Therefore they must be stored temporarily from that they are read from the network until the client is ready to handle them. Read but unhandled events are stored on an event queue in the Display object. There are two functions to access this queue:

Method on Display: next_event ( )

Return the next event in the event queue. If the event queue is empty, block until an event is read from the network, and return that one.

Method on Display: pending_events ( )

Return the number of events which can be returned without blocking.

A trivial event loop would simply loop infinitely, waiting for an event and then handling it. It could look like this:

while 1:
   event = disp.next_event()

However, most applications need more control, e.g. to simultaneously handle a network connection or at regular intervals schedule timeouts. The module select is often used for this. Display objects can be used with select, since they have the required fileno() method. When select indicates that a Display object is ready for reading, that means that the server has sent some data to the client. That alone doesn’t guarantee that an entire event has arrived, so one must first use pending_events() to make sure that next_event() will return without blocking. A simple event loop which waits for events or a one-second timeout looks like this:

while 1:
    # Wait for display to send something, or a timeout of one second
    readable, w, e = select.select([disp], [], [], 1)

    # if no files are ready to be read, it's an timeout
    if not readable:

    # if display is readable, handle as many events as have been received
    elif disp in readable:
        i = disp.pending_events()
        while i > 0:
            event = disp.next_event()
            i = i - 1

    # loop around to wait for more things to happen

[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

This document was generated on September 16, 2020 using texi2html 5.0.