Search code examples
pythonopenglpygletopengl-compat

why does my window doesn't work for on_draw?


I was watching a video about pyglet and I tried to create a triangle:

import pyglet
from pyglet.gl import *

class mywindow(pyglet.window.Window):
    def __init__(self, *args,**kwargs):
        super().__init__(*args,**kwargs)
        self.set_minimum_size(300,300)
        
window = mywindow(300,300,"deneme", True)

def on_draw():
    glBegin(GL_TRIANGLE)
    glColor3b(255,0,0)
    glVertex2f(-1,0)
    glColor3b(0,255,0)
    glVertex2f(1,0)
    glColor3b(0,0,255)
    glVertex2f(0,1)

window.on_draw()
pyglet.app.run()

    

when I run this code; I get this error:

AttributeError: 'mywindow' object has no attribute 'on_draw'

Any idea how to solve this?


Solution

  • on_draw has to be a method of the class mywindow rather than a function. Don't invoke on_draw yourself, because it is called automatically, when the window is needed to be updated.
    At the begin of on_draw you've to clear the display by (see Windowing).
    A OpenGL immediate mode glBegin/glEnd sequence has to be ended by glEnd. The primitive type is GL_TRIANGLES rather than GL_TRIANGLE. If you want to specify the colors in range [0, 255], the you've to use glColor3ub (unsigned byte) rather then glColor3b (signed byte).
    You have to set the viewport rectangle of the resizable window by glViewport in the on_resize event.

    See the example:

    import pyglet
    from pyglet.gl import *
    
    class mywindow(pyglet.window.Window):
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self.set_minimum_size(300,300)
    
        def on_draw(self):
    
            self.clear()
    
            glBegin(GL_TRIANGLES)
            glColor3ub(255, 0, 0)
            glVertex2f(-1, 0)
            glColor3ub(0, 255, 0)
            glVertex2f(1, 0)
            glColor3ub(0, 0, 255)
            glVertex2f(0, 1)
            glEnd()
    
        def on_resize(self, width, height):
            glViewport(0, 0, width, height)
    
    window = mywindow(300,300,"deneme", True)
    pyglet.app.run()