Keyboard function does not work PyOpenGL

1

I have the following code, I wanted to make a simple event to close the application but my keyboard function does not work, I looked elsewhere and I found similar versions. If you can help me, thank you.

from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *

import OpenGL.GL
import sys, struct



def desenha():
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

    glPointSize(5.0)
    glBegin(GL_POINTS)
    glColor3fv((0,1,0))
    glVertex3f(0.0, 0.0, 0.0)
    glColor3fv((1,0,1))
    glVertex3f(0.0, 0.1, 0.0)
    glColor3fv((1,0,1))
    glVertex3f(0.1, 0.0, 0.0)
    glColor3fv((1,0,1))
    glVertex3f(0.0, -0.1, 0.0)
    glColor3fv((1,0,1))
    glVertex3f(-0.1, 0.0, 0.0)

    glEnd()
    glutSwapBuffers()

def keyboard(key, x, y):
    if key == chr(97):
        sys.exit(0)
    return 0


def main():
    glutInit([])
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB| GLUT_DEPTH | GLUT_ALPHA)
    #glutInitWindowSize(400,400)
    glutCreateWindow(b'This is my title')
    glutInitWindowPosition(100, 100)
    glutDisplayFunc(desenha)
    glutKeyboardFunc(keyboard)

    glutCreateMenu(nome)
    glutMainLoop()


main()
    
asked by anonymous 07.06.2015 / 22:51

1 answer

1

A glutkeyboardFunc documentation in

says that the signature of the telecloser's processing function is:

def handler( (int) key, (int) x, (int) y ):
    return None

That is, you get the code number of the key (a number) - and in your code you compare that number with a character - (the result of the call to chr(97) which in this case is a string with the letter "a" ). The result of this is always false. Maybe you have seen some sample code in C where casting (char)97 is essentially a "no operation" - internally your die is still the number 97.

In Python, or you compare numbers directly -

if key == 97

Or, to improve readability, compare the character represented by the received code with the desired character. That is: you transform the received number into a character:

if chr (key) == "a":         ...

If you opt for this one more detail - the received code may be outside the 0-255 range, and there the call to chr would give an error - so make sure the numeric code is on track:

def keyboard(key, x, y):
    if 0 <= key <= 255 and chr(key) == "a":
        sys.exit(0)
    return None

(Note that it is also interesting to leave the return value as None, as suggested in the documentation.) In Python, this is different from returning "0" - which you may have also seen in some example in C) >     

08.06.2015 / 07:37