Example implementation of custom EventLoop in Pyglet


Eventloop in Pyglet is a great feature when we want to control or integrate run() into another loop (eg: reactor.run() on twisted). In their documentation, http://www.pyglet.org/doc/programming_guide/customising_the_event_loop.html, the example of using custom eventloop in pyglet isn’t clear.

Here is example how to use EventLoop() in Pyglet to control the loop without pyglet.app.run():

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
from pyglet import window, text, app, resource, event, clock

event_loop = app.EventLoop()
fps_display = clock.ClockDisplay()

window = window.Window()
image = resource.image("ball.png")

@window.event
def on_draw():
    window.clear()
    image.blit(100, 100)
    fps_display.draw()


@event_loop.event
def on_window_close(window):
    event_loop.exit()
    return event.EVENT_HANDLED

def main():
    event_loop.run()

if __name__ == "__main__":
    main()

So, basically, we create a new instance from EventLoop by:

1
event_loop = app.EventLoop()

And we can start this event_loop by execute run() method from the instance.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.