我正在尝试使用 PyOpenGL 在 Python 中编写程序,我需要使用 glutMouseFunc 来实现某些鼠标功能,但是当我运行程序时出现以下错误:
Traceback (most recent call last):
File "teapot.py", line 80, in <module>
glutMouseFunc(mouseHandle)
File "/usr/lib/python2.7/dist-packages/OpenGL/GLUT/special.py", line 137, in __call__
contextdata.setValue( self.CONTEXT_DATA_KEY, cCallback )
File "/usr/lib/python2.7/dist-packages/OpenGL/contextdata.py", line 57, in setValue
context = getContext( context )
File "/usr/lib/python2.7/dist-packages/OpenGL/contextdata.py", line 40, in getContext
"""Attempt to retrieve context when no valid context"""
OpenGL.error.Error: Attempt to retrieve context when no valid context
我尝试用谷歌搜索,但找不到任何相关结果。这是我的代码:
from OpenGL.GL import *
from OpenGL.GLUT import *
t = 0
def init():
r=1
g=0
b=0
glColor3f(r,g,b)
glClearColor(1.0,1.0,1.0,0.0)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
def display():
glClear(GL_COLOR_BUFFER_BIT)
glViewport(0,0,150,100)
drawSquare()
glViewport(0,100,150,200)
drawCircle()
glViewport(0,200,150,300)
drawTriangle()
glViewport(0,300,150,400)
drawFan()
if(t==1):
glViewport(150,0,800,600)
drawFan()
if(t==2):
glViewport(150,0,800,600)
drawTriangle()
if(t==3):
glViewport(150,0,800,600)
drawCircle()
if(t==4):
glViewport(150,0,800,600)
drawSquare()
glFlush()
def drawFan():
glBegin(GL_TRIANGLE_FAN)
glVertex2f(0.0,0.0)
glVertex2f(0.3,0.3)
glVertex2f(0.3,-0.3)
glVertex2f(-0.3,0.3)
glVertex2f(-0.3,-0.3)
glEnd()
def drawTriangle():
glBegin(GL_TRIANGLES)
glVertex2f(0.5,0.0)
glVertex2f(0.0,0.5)
glVertex2f(-0.5,0.0)
glEnd()
def drawCircle():
glutSolidSphere(0.5, 30 ,30)
def drawSquare():
glBegin(GL_POLYGON)
glVertex2f(0.5,0.5)
glVertex2f(-0.5,0.5)
glVertex2f(-0.5,-0.5)
glVertex2f(0.5,-0.5)
glEnd()
def mouseHandle(button, state, x, y):
if(button == GLUT_LEFT_BUTTON and x < 150 and y < 170):
t=1
glutPostRedisplay()
print "1: x=",x," y=",y,"\n"
elif(button == GLUT_LEFT_BUTTON and x < 150 and 170 < y and y < 280):
t=2
glutPostRedisplay()
elif(button == GLUT_LEFT_BUTTON and x < 150 and 345 < y and y < 451):
t=3
glutPostRedisplay()
elif(button == GLUT_LEFT_BUTTON and x < 150 and 525 < y and y < 578):
t=4
glutPostRedisplay()
else:
glutPostRedisplay()
glutInit('')
glutMouseFunc(mouseHandle)
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB)
glutInitWindowSize(800,600)
glutCreateWindow('Hello GLUT')
glutDisplayFunc(display)
init()
glutMainLoop()