简体   繁体   中英

PYGame - How to stop and close window by pressing a Key?

I have created a script using PYGAME to animate a pendulum motion simulation. I want to press a "q" key to stop the simulation and close the window. I tryed many different codes but all return some error. The lest version of the event part of the code was:

done = False
while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
            
        if event.type == KEYDOWN:
            if event.key == K_t:
                is_tracing = not(is_tracing)
            if event.key == K_c:
                trace.fill(WHITE)
            if event.key == K_q:
                done = True
        break

The "c" and "t" events are running fina and the "q" idead stops the simulation, but the simulation window frezes and I need to reestart the kernel do make it run again. Any idea of how to make it close the window without Killing the kernel?

I am runing the code at Jupter Notebook 6.1.4 from Anaconda Navigator 1.10 and Python 3.8.5

Any idea of how to make it close the window without Killing the kernel?

Try using pygame.quit() . From pygame FAQ

Make sure, you invoke pygame.quit() on exiting your application or game.

# ... running = True
while running:
    event = pygame.event.wait ()
    if event.type == pygame.QUIT:
        running = False  # Be IDLE friendly
pygame.quit ()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM