你错过了key_callback中的global statement:
def key_callback(window, key, scancode, action, mods):
global currentMode # <--- THIS IS MISSING
if key==glfw.KEY_1:
if action==glfw.PRESS:
currentMode = GL_POINTS
# [...]
变量currentMode 存在两次。它是全局命名空间中的变量,也是函数key_callback 范围内的局部变量。使用global 语句将currentMode 解释为全局变量,并将key_callback 写入全局变量currentMode。
当然,main 函数也是如此:
def main():
global currentMode
# [...]
此外,您必须清除 render 中的帧缓冲区:
def render(currentMode):
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
看例子:
import glfw
from OpenGL.GL import *
import numpy as np
def render(currentMode):
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glLoadIdentity()
print(currentMode)
glBegin(currentMode)
#Draw Something
glVertex2f(-0.5, -0.5)
glVertex2f(0.5, 0.5)
glVertex2f(-0.5, 0.5)
glEnd()
def key_callback(window, key, scancode, action, mods):
global currentMode
if key==glfw.KEY_1:
if action==glfw.PRESS:
currentMode = GL_POINTS
elif key==glfw.KEY_2:
if action==glfw.PRESS:
currentMode = GL_LINES
elif key==glfw.KEY_3:
if action==glfw.PRESS:
currentMode = GL_LINE_STRIP
def main():
global currentMode
if not glfw.init():
return
window = glfw.create_window(480, 480, "Test", None, None)
if not window:
glfw.terminate()
return
glfw.make_context_current(window)
glfw.set_key_callback(window, key_callback)
glfw.swap_interval(1)
while not glfw.window_should_close(window):
glfw.poll_events()
render(currentMode)
glfw.swap_buffers(window)
glfw.terminate()
if __name__ == "__main__":
currentMode = GL_LINE_LOOP
main()