Fix for pygame/PyOpenGL/NeHe tutorial windows not disappearing when run from IDLE

30 August 2009

It’s a long weekend here in the UK and I thought I’d spend some time working through Paul Furber’s Python translations of the well-known NeHe OpenGL tutorial, which use the pygame and PyOpenGL libraries. (This is all with Python 2.6 on Windows XP.)

I noticed that when I ran the sample files from IDLE, the windows did not close — it didn’t matter whether I used the close box or hit escape; the program would seem to exit, but IDLE was in a messy state, and the OpenGL window would sit there not repainting.

Googling didn’t turn up anything that sounded relevant, but this archived mailing list message mentioned a pygame.quit() function that sounded relevant. I tried putting this at the end of each of the samples, and it seems to fix the problem.

[UPDATE: Of course, this fix is even better if put into a finally block, because then you’re covered when you introduce errors into the OpenGL code. Example below fixed appropriately.]

[Further UPDATE: Looks like this is the right thing to do — non-OpenGL Pygame FAQ here.]

An example:

def main():

    video_flags = OPENGL|DOUBLEBUF
    
    pygame.init()
    try:
        pygame.display.set_mode((640,480), video_flags)

        resize((640,480))
        init()

        frames = 0
        ticks = pygame.time.get_ticks()
        while 1:
            event = pygame.event.poll()
            if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
                break
        
            draw()
            pygame.display.flip()
            frames = frames+1

        print "fps:  %d" % ((frames*1000)/(pygame.time.get_ticks()-ticks))
    finally:
        pygame.quit()

Caveat: I’m a complete n00b with all of the technologies involved (except, debatably, Python), so this may be completely the wrong solution. But it works well enough for me to keep going with the tutorials for now.