PyOpenGL

3.1.10 · active · verified Fri Apr 10

PyOpenGL (version 3.1.10) provides standard OpenGL bindings for Python, allowing Python programs to interact directly with OpenGL graphics APIs. It offers access to both core OpenGL functionality and extensions, enabling development of 2D/3D graphics applications. The library is mature and stable, with a moderate release cadence driven by bug fixes and OpenGL specification updates.

Warnings

Install

Imports

Quickstart

This example demonstrates basic PyOpenGL usage with GLUT to create a window and draw a simple colored triangle. It uses the traditional fixed-function pipeline for simplicity. Ensure you have GLUT installed on your system (e.g., `freeglut3-dev` on Debian/Ubuntu, or a GLUT for Windows build).

import sys
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *

def draw_triangle():
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    glLoadIdentity()
    glTranslatef(0.0, 0.0, -5.0)

    glBegin(GL_TRIANGLES)
    glColor3f(1.0, 0.0, 0.0)  # Red
    glVertex3f(-1.0, -1.0, 0.0)
    glColor3f(0.0, 1.0, 0.0)  # Green
    glVertex3f(1.0, -1.0, 0.0)
    glColor3f(0.0, 0.0, 1.0)  # Blue
    glVertex3f(0.0, 1.0, 0.0)
    glEnd()

    glutSwapBuffers()

def reshape(width, height):
    glViewport(0, 0, width, height)
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    gluPerspective(45, (width / height), 0.1, 50.0)
    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity()

def keyboard(key, x, y):
    if key == b'\x1b': # ESC key
        sys.exit()

def main():
    glutInit(sys.argv)
    glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH)
    glutInitWindowSize(600, 600)
    glutInitWindowPosition(100, 100)
    glutCreateWindow(b"PyOpenGL Triangle (ESC to exit)")

    glClearColor(0.2, 0.2, 0.2, 1.0) # Dark gray background
    glEnable(GL_DEPTH_TEST)

    glutDisplayFunc(draw_triangle)
    glutIdleFunc(draw_triangle) # Redraw continuously
    glutReshapeFunc(reshape)
    glutKeyboardFunc(keyboard)

    glutMainLoop()

if __name__ == '__main__':
    main()

view raw JSON →