我正在尝试使用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()
答案 0 :(得分:0)
好的,在一些住宅之后我发现了如何解决它。我必须在glutMouseFunc
之后移动glutDisplayFunc
来电,如下所示:
glutInit('')
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB)
glutInitWindowSize(800,600)
glutCreateWindow('Hello GLUT')
glutDisplayFunc(display)
glutMouseFunc(mouseHandle)
init()
glutMainLoop()