Question

I want to subclass pyglet.window.Window, but this code throw me exceptions for super in on_draw() and in on_mouse_pressed()

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import pyglet


class Window(pyglet.window.Window):
    def __init__(self, *arguments, **keywords):
        super(Window, self).__init__(*arguments, **keywords)

    def on_draw(self):
        super(Window, self).on_draw()
        self.clear()

    def on_key_press(self, symbol, modifiers):
        super(Window, self).on_key_press(symbol, modifiers)
        if symbol == pyglet.window.key.A:
            print "A"

    def on_mouse_press(self, x, y, button, modifiers):
        super(Window, self).on_mouse_press(x, y, button, modifiers)
        if button:
            print button


window = Window()
pyglet.app.run()

Whereas this code doesn't. Why it this? Is safe use super in Pyglet events?

The default on_draw() in pyglet.window.Window call flip() but I can't call on_draw() of pyglet.window.Window and I can't find where on_draw() is defined in Pyglet modules. Where is this defined and why I can't call on_draw() of pyglet.window.Window with super?

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import pyglet


class Window(pyglet.window.Window):
    def __init__(self, *arguments, **keywords):
        super(Window, self).__init__(*arguments, **keywords)

    def on_draw(self):
        self.clear()

    def on_key_press(self, symbol, modifiers):
        super(Window, self).on_key_press(symbol, modifiers)
        if symbol == pyglet.window.key.A:
            print "A"

    def on_mouse_press(self, x, y, button, modifiers):
        if button:
            print button


window = Window()
pyglet.app.run()
Was it helpful?

Solution

There is no on_draw or on_mouse_press function defined for pyglet.window.Window, so you cannot call them. In the base class, these only exist as registered event types, which means that when the window receives one of them through dispatch_event(), it will first check its event stack for a handler, then its own attributes for a function with a matching name. If there is no match in either place, the event is ignored. This is what allows you to define a handler directly as you did in your code, or by using a decorator outside the class to push a handler onto the stack (or both).

The EventLoop does dispatch an on_draw event to each window during every iteration, but flip() is called separately.

Source:

class EventLoop(event.EventDispatcher):
    # ...
    def idle(self):
        # ...
        # Redraw all windows
        for window in app.windows:
            if redraw_all or (window._legacy_invalid and window.invalid):
                window.switch_to()
                window.dispatch_event('on_draw')
                window.flip()
                window._legacy_invalid = False
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top