Python 3.6.2 安装 GLFW 及实例
GLFW 是一个窗口工具包
1、 下载 GLFW。它可以在 http://www.glfw.org/download.html 这个网页上下载。
2、 将下载的压缩文件 glfw-3.2.1.bin.WIN32 (1).zip 解压到我的文件夹内,D:\OpenGL\Glew
文件夹\glfw-3.2.1.bin.WIN32 (1)\glfw-3.2.1.bin.WIN32。
3、 将 GLFW 的库文件位置添加到环境变量中的 path 中。点击“我的电脑”右键选择“属
性”,弹出窗口,然后依次点击“高级系统设置”,“高级”,“环境变量”,点击“编辑”,
“ 新 建 ” , 将 D:\OpenGL\Glew 文 件 夹 \glfw-3.2.1.bin.WIN32
(1)\glfw-3.2.1.bin.WIN32\lib-vc2015 文件夹添加进去. (注意:此处的目录应该是读
者自己下载的 GLFW 安装目录。其中目录 lib-vc2015 是库文件所在文件夹)。
4、 路径设置完成后,要关闭你的 python 编译软件然后重新打开,你就可以在 python 中
使用 GLFW 了。
5、 导入 glfw >>> import glfw
6、 查看包帮助 >>> help(glfw)
7、 运行例子程序,因为导入的 glfw 中的函数名都不带 GLFW,所以将 simple.py 中相应函数
都做了对应的修改,运行结果及源程序如下:
if __name__ == '__main__':
import sys
import glfw
import OpenGL.GL as gl
def on_key(window, key, scancode, action, mods):
if key == glfw.KEY_ESCAPE and action == glfw.PRESS:
glfw.set_window_should_close(window,1)
# Initialize the library
if not glfw.init():
sys.exit()
# Create a windowed mode window and its OpenGL context
window = glfw.create_window(640, 480, "Hello World", None, None)
if not window:
glfw.terminate()
sys.exit()
# Make the window's context current
glfw.make_context_current(window)
# Install a key handler
glfw.set_key_callback(window, on_key)
# Loop until the user closes the window
while not glfw.window_should_close(window):
# Render here
width, height = glfw.get_framebuffer_size(window)
ratio = width / float(height)
gl.glViewport(0, 0, width, height)
gl.glClear(gl.GL_COLOR_BUFFER_BIT)
gl.glMatrixMode(gl.GL_PROJECTION)
gl.glLoadIdentity()
gl.glOrtho(-ratio, ratio, -1, 1, 1, -1)
gl.glMatrixMode(gl.GL_MODELVIEW)
gl.glLoadIdentity()
# gl.glRotatef(glfw.get_time() * 50, 0, 0, 1)
gl.glBegin(gl.GL_TRIANGLES)
gl.glColor3f(1, 0, 0)
gl.glVertex3f(-0.6, -0.4, 0)
gl.glColor3f(0, 1, 0)
gl.glVertex3f(0.6, -0.4, 0)
gl.glColor3f(0, 0, 1)
gl.glVertex3f(0, 0.6, 0)
gl.glEnd()
# Swap front and back buffers
glfw.swap_buffers(window)
# Poll for and process events
glfw.poll_events()
glfw.terminate()