Python中OpenGL 2D点延迟绘制异常:一次性显示所有点
解决GLUT中依次绘制元素延迟显示的问题
问题现象
编写GLUT代码尝试每隔1秒依次绘制3个点,但实际运行时窗口先空白3秒,之后一次性显示所有三个点,不符合预期。
问题原因
- 线程阻塞:
showScreen回调运行在GLUT的渲染主线程中,time.sleep(1)会直接阻塞主线程,导致所有绘制操作都在三次阻塞完成后才执行,最后通过glutSwapBuffers一次性刷新到窗口。 - 颜色参数错误:
glColor3f的参数取值范围是0.0~1.0,原代码传入255会被截断为1.0,虽能显示白色但不符合API规范。
解决方案
使用GLUT的glutTimerFunc实现非阻塞式的定时绘制,通过全局变量跟踪绘制进度,每次定时器触发时更新进度并触发窗口重绘。
修改后的代码
from OpenGL.GL import * from OpenGL.GLUT import * from OpenGL.GLU import * # 全局变量:记录当前已绘制的点数量 point_count = 0 # 定义要绘制的点坐标列表 points = [(200, 200), (300, 300), (400, 400)] def draw_points(x0, y0): glPointSize(5) glBegin(GL_POINTS) glVertex2f(x0, y0) glEnd() def iterate(): glViewport(0, 0, 1000, 1000) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0.0, 1000, 0.0, 1000, 0.0, 1.0) glMatrixMode(GL_MODELVIEW) glLoadIdentity() def showScreen(): glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glLoadIdentity() iterate() glColor3f(1.0, 1.0, 1.0) # 使用0.0~1.0的浮点数作为颜色参数 # 根据当前进度绘制对应数量的点 for i in range(point_count): draw_points(*points[i]) glutSwapBuffers() def update_point_count(value): global point_count if point_count < len(points): point_count += 1 glutPostRedisplay() # 标记窗口需要重绘 # 1000毫秒后再次触发定时器,继续绘制下一个点 glutTimerFunc(1000, update_point_count, 0) glutInit() glutInitDisplayMode(GLUT_RGBA) glutInitWindowSize(1000, 1000) glutInitWindowPosition(0, 0) wind = glutCreateWindow(b"") glutDisplayFunc(showScreen) # 启动定时器:1000毫秒后第一次触发,开始绘制第一个点 glutTimerFunc(1000, update_point_count, 0) glutMainLoop()
代码说明
point_count全局变量跟踪已绘制的点数量,初始为0glutTimerFunc(1000, update_point_count, 0):注册一个1秒后触发的定时器,调用update_point_count函数update_point_count:每次触发时增加point_count,调用glutPostRedisplay()通知GLUT需要重绘窗口,然后再次注册定时器(直到所有点绘制完成)showScreen在每次重绘时,根据当前point_count绘制对应数量的点,保证每次重绘只显示到当前进度的点
内容的提问来源于stack exchange,提问作者Md. Anas Mahmud
相关产品推荐
相关产品推荐

