Pyglet Triangle Color Draw and Escape Close Window

  • Share this:

Code introduction


This function uses the Pyglet library to create a window and draw a triangle composed of red, green, and blue colors in it. It also listens to keyboard events, closing the window when the ESC key is pressed.


Technology Stack : Pyglet

Code Type : Graphical interface

Code Difficulty : Intermediate


                
                    
def random_color_draw(x, y):
    from pyglet.gl import *
    from pyglet.window import key

    def on_draw():
        glClear(GL_COLOR_BUFFER_BIT)
        glBegin(GL_TRIANGLES)
        glColor3f(1, 0, 0)  # Red
        glVertex2f(x, y)
        glColor3f(0, 1, 0)  # Green
        glVertex2f(x + 50, y + 50)
        glColor3f(0, 0, 1)  # Blue
        glVertex2f(x, y + 100)
        glEnd()

    def on_key_press(symbol, modifiers):
        if symbol == key.ESCAPE:
            window.close()

    window = pyglet.window.Window()
    window.on_draw = on_draw
    window.on_key_press = on_key_press
    pyglet.app.run()                
              
Tags: