Python Bindings for GLFW
glfw (pyGLFW) is a ctypes-based wrapper for GLFW3, a cross-platform library for OpenGL, OpenGL ES and Vulkan development. It simplifies window creation, context management, and input handling in Python, providing a near one-to-one mapping to the C API with Pythonic naming conventions. The current version is 2.10.0, and it maintains an active release cadence with regular updates.
Warnings
- breaking The pyGLFW API (current 'glfw' PyPI package) translates GLFW C functions from `camelCase` with a `glfw` prefix (e.g., `glfwGetVersion`) to Pythonic `snake_case` without the prefix (e.g., `glfw.get_version()`). Similarly, constants like `GLFW_KEY_ESCAPE` become `glfw.KEY_ESCAPE`. Code written for the direct C API or older Python wrappers will need adaptation.
- gotcha Despite Python wheels often including the GLFW C shared library for convenience (Windows, macOS, Linux), an `ImportError: Failed to load GLFW3 shared library` can occur. This usually means the native GLFW C library is not found or is incompatible. Users might need to install it via their system's package manager (e.g., `sudo apt install libglfw3 libglfw3-dev` on Debian/Ubuntu, `brew install glfw` on macOS) or compile it from source, ensuring the shared library is discoverable.
- gotcha Version `2.7.0` included GLFW 3.4 functions in the Python wrapper but explicitly noted that GLFW 3.4 was *not* included in Python wheels due to build issues on various systems (e.g., manylinux 2014). This could lead to unexpected behavior or missing functionality if a user expected bundled GLFW 3.4 features. This was resolved in `2.8.0` with an update to GLFW 3.4.
- gotcha When distributing applications with tools like cx_Freeze or PyInstaller, `glfw` might struggle to locate the bundled GLFW shared library, especially on non-Windows platforms. While `glfw` has built-in search logic for frozen executables, custom setups might still fail.
Install
-
pip install glfw
Imports
- glfw
import glfw
Quickstart
import glfw
import OpenGL.GL as gl
def main():
# Initialize the library
if not glfw.init():
raise RuntimeError("Failed to initialize GLFW")
# Create a windowed mode window and its OpenGL context
window = glfw.create_window(640, 480, "Hello pyGLFW", None, None)
if not window:
glfw.terminate()
raise RuntimeError("Failed to create GLFW window")
# Make the window's context current
glfw.make_context_current(window)
# Set viewport and clear color
gl.glViewport(0, 0, 640, 480)
gl.glClearColor(0.2, 0.3, 0.4, 1.0)
# Loop until the user closes the window
while not glfw.window_should_close(window):
# Render here
gl.glClear(gl.GL_COLOR_BUFFER_BIT)
# Swap front and back buffers
glfw.swap_buffers(window)
# Poll for and process events
glfw.poll_events()
glfw.terminate()
if __name__ == "__main__":
main()