You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用GLUT创建可调整大小的窗口?PyOpenGL macOS环境问题

macOS下GLUT窗口无法调整大小的解决方法

核心修改

在创建窗口前显式开启窗口可调整属性,只需在glutCreateWindow之前添加一行代码:

glutSetWindowAttr(GLUT_RESIZABLE, 1)

修改后的完整代码

from OpenGL.GLUT import *
from OpenGL.GL import *
from OpenGL.GLU import *
import sys  # 补充导入sys,原代码缺失会触发NameError

def change_size(w, h):
    glViewport(0, 0, w, h)
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    aspect_ratio = w/h
    if w <= h:
        glOrtho(-100, 100, -100/aspect_ratio, 100/aspect_ratio, 1, -1)
    else:
        glOrtho(-100*aspect_ratio, 100*aspect_ratio, -100, 100, 1, -1)
    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity()
    

def render_scene():
    glClear(GL_COLOR_BUFFER_BIT)
    glColor(1,0,0,0)
    glRectf(-25,25,25,-25)
    glFlush()
        
def setup_rc():
    glClearColor(0, 0, 1, 1)
    
def main():
    glutInit(sys.argv)
    glutInitDisplayMode(GLUT_SINGLE|GLUT_RGBA)
    glutSetWindowAttr(GLUT_RESIZABLE, 1)  # 启用窗口调整功能
    glutCreateWindow("Simple")
    glutDisplayFunc(render_scene)
    glutReshapeFunc(change_size)
    setup_rc()
    glutMainLoop()
    
main()

说明

macOS平台的GLUT(包括freeglut)默认创建固定大小窗口,必须通过glutSetWindowAttr(GLUT_RESIZABLE, 1)显式启用窗口调整功能。你的change_size回调逻辑无需修改,添加上述设置后,窗口调整时会自动触发该函数更新视口和投影矩阵。

内容的提问来源于stack exchange,提问作者PaulM

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 07:20:00