Keyboard function does not work Pyopengl

Asked

Viewed 112 times

1

Guys I have the following code, I wanted to make a simple event to close the application but my function Keyboard does not work, I searched elsewhere and found similar versions. If you can help me, I’d appreciate it.

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()

1 answer

1


To glutkeyboardFunc documentation in

says that the signature of the treatment function of teeclade is:

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

That is, you receive the numeric code of the key (a number) - and in your code you compare this 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 example code in C where the casting (char)97 is essentially a "no Operation" - internally your data remains the number 97.

In Python, or you compare the numbers directly -

if key == 97

Or, to improve readability, compare the character represented by the received code with the desired character. In other words: you turn the number received into character:

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

If you choose this form to one more detail - the code received may be outside the range 0-255, and then the call to chr would give an error - so make sure that the numeric code is in that range:

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 is suggested in the documentation. In Python, this is different from returning "0" - which you might have seen in some example in C)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.