出于加深学习效果,自己试着用Python重新实现原教程中的C++代码
1. 操作系统:Windows 10
3. 安装pyOpenGl: 安装完python后默认会同时安装pip, 将pip加入默认路径,在windows命令行窗口输入 pip install PyOpenGL
4. 下载GLFW:在http://www.glfw.org/download.html 下载 32-bit Windows binaries,下到的压缩文件解压后,得到库文件lib-vc2015/glfw3.dll
5. 下载GLFW的python 接口文件:在https://github.com/rougier/pyglfw下载glfw.py,并将其和上一步得到的库文件放到python默认的库目录或当前开发代码的同级目录中
6. 创建window.py文件,代码如下:
#! /usr/bin/env python#-*- coding: utf-8 -*-
importsys, osimportOpenGL.GL as glimportglfw
WIN_WIDTH= 800WIN_HEIGHT= 600
defframebuffer_size_callback(window, width, height):
gl.glViewport(0, 0, width, height)defprocessInput(window):if glfw.glfwGetKey(window, glfw.GLFW_KEY_ESCAPE) ==glfw.GLFW_PRESS:
glfw.glfwSetWindowShouldClose()defmain():
glfw.glfwInit()
glfw.glfwWindowHint(glfw.GLFW_CONTEXT_VERSION_MAJOR,3)
glfw.glfwWindowHint(glfw.GLFW_CONTEXT_VERSION_MINOR,3)
glfw.glfwWindowHint(glfw.GLFW_OPENGL_PROFILE, glfw.GLFW_OPENGL_CORE_PROFILE)
window= glfw.glfwCreateWindow(WIN_WIDTH, WIN_HEIGHT, "学习OpenGL".encode(), 0, 0)if window ==0:print("failed to create window")
glfw.glfwTerminate()
glfw.glfwMakeContextCurrent(window)
glfw.glfwSetFramebufferSizeCallback(window, framebuffer_size_callback)while notglfw.glfwWindowShouldClose(window):
processInput(window)
gl.glClearColor(0.2, 0.3, 0.3, 1.0)
gl.glClear(gl.GL_COLOR_BUFFER_BIT)
glfw.glfwSwapBuffers(window)
glfw.glfwPollEvents()
glfw.glfwTerminate()if __name__ == "__main__":
main()
该段代码执行后得到的效果如下:
或对应的的中文教程