Search code examples
pythonpyglet

How is this method called? (Pyglet)


The following code is an alternative to the usual style (using decorators) pyglet makes use of.

Can anyone explain how the on_draw() method is called here?

import pyglet

class HelloWorldWindow(pyglet.window.Window): 
    def __init__(self):
        super(HelloWorldWindow, self).__init__() 
        self.label = pyglet.text.Label('Hello, world!') 

    def on_draw(self):
        self.clear() 
        self.label.draw() 

if __name__ == '__main__':
    window = HelloWorldWindow() 
    pyglet.app.run()

The code written using decorators can be found here.


Solution

  • You can just dig through the source to find the answer.

    The EventLoop class (you use it by pyglet.app.run()) dispatches the on_draw event regulary.

    From the source:

    Calling run begins the application event loop, which processes operating system events, calls pyglet.clock.tick to call scheduled functions and calls pyglet.window.Window.on_draw and pyglet.window.Window.flip to update window contents.

    The Window class subscripes to this event:

    BaseWindow.register_event_type('on_draw')
    

    So by subclassing Window, you ensure your on_draw method gets called.

    Look at the programming guide for an example of how the event system of pyglet works.