当我关闭时,Pygame屏幕会冻结

时间:2011-04-11 01:03:52

标签: python pygame

代码加载了一个pygame屏幕窗口,但是当我单击X关闭它时,它变得没有响应。我正在运行64位系统,使用32位python和32位pygame。

from livewires import games, color

games.init(screen_width = 640, screen_height = 480, fps = 50)

games.screen.mainloop()

5 个答案:

答案 0 :(得分:8)

Mach1723的answer是正确的,但我想建议一个主循环的另一种变体:

while 1:
    for event in pygame.event.get():
        if event.type == QUIT: ## defined in pygame.locals
            pygame.quit()
            sys.exit()

        if event.type == ## Handle other event types here...

    ## Do other important game loop stuff here.

答案 1 :(得分:4)

我推荐以下代码。首先,它包括时钟,所以你的程序不会吃CPU除了轮询事件。其次,它调用pygame.quit()来阻止程序在Windows上的IDLE下运行时冻结。

# Sample Python/Pygame Programs
# Simpson College Computer Science
# http://cs.simpson.edu/?q=python_pygame_examples

import pygame

# Define some colors
black    = (   0,   0,   0)
white    = ( 255, 255, 255)
green    = (   0, 255,   0)
red      = ( 255,   0,   0)

pygame.init()

# Set the height and width of the screen
size=[700,500]
screen=pygame.display.set_mode(size)

pygame.display.set_caption("My Game")

#Loop until the user clicks the close button.
done=False

# Used to manage how fast the screen updates
clock=pygame.time.Clock()

# -------- Main Program Loop -----------
while done==False:
    for event in pygame.event.get(): # User did something
        if event.type == pygame.QUIT: # If user clicked close
            done=True # Flag that we are done so we exit this loop

    # Set the screen background
    screen.fill(black)

    # Limit to 20 frames per second
    clock.tick(20)

    # Go ahead and update the screen with what we've drawn.
    pygame.display.flip()

# Be IDLE friendly. If you forget this line, the program will 'hang'
# on exit.
pygame.quit ()

答案 2 :(得分:2)

这是一个非常简单的问题,您需要处理“QUIT”事件,请参阅以下内容的事件文档:http://www.pygame.org/docs/ref/event.html

编辑: 现在我发现你可能正在处理“QUIT”事件并且它无法正常工作 但是没有更多关于你的代码的细节我不知道。

处理“QUIT”事件的简单方法的简单示例:

import sys
import pygame

# Initialize pygame
pygame.init()
pygame.display.set_mode(resolution=(640, 480))

# Simple(ugly) main loop
curEvent = pygame.event.poll()

while curEvent.type != pygame.QUIT:
      # do something
      curEvent = pygame.event.poll()

答案 3 :(得分:2)

在使用pygame时,你必须处理所有事件,包括QUIT,所以如果你不处理quit事件,你的程序将不会退出。这是一个代码。

import sys
import pygame
from pygame.locals import *

def main():
    running = True
    while running:
        for event in pygame.event.get():
            if event.type==QUIT: #QUIT is defined at pygame.locals 
                runnning = False
    #other game stuff to be done

if __name__=='__main__':
    pygame.init()
    pygame.display.set_mode((640,480))
    main()

答案 4 :(得分:1)

要使pygame窗口可关闭很简单,使用函数while True:制作游戏循环然后在此使用函数for event in pygame.event.get():创建for循环,接下来添加代码{{1}如果你已经创建了一个'while True'循环,你只需要添加最后一段代码。现在添加if event.type == QUIT:pygame.quit(),这是完成的代码:

sys.exit()

请注意,您需要先导入pygame和sys。

相关问题