我无法在 OpenGL 和 glfw 中使用 keyCallback 函数

I can't make working keyCallback function in OpenGL and glfw

import glfw
from OpenGL.GL import *
import numpy as np

currentMode = GL_LINE_LOOP

def render(currentMode):


def key_callback(window, key, scancode, action, mods):
    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

while not glfw.window_should_close(window):
    glfw.poll_events()
    render(currentMode)
    glfw.swap_buffers(window)
    print(currentMode)
glfw.terminate()

我尝试更改基本类型以使用渲染函数的参数。 但是,它不起作用。 我该怎么办?

您错过了 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()