2011-04-11 173 views
3

代碼加載pygame屏幕窗口,但是當我點擊X關閉它,它變得沒有響應。我在64位系統上運行,使用32位python和32位pygame。Pygame屏幕凍結時,我關閉它

from livewires import games, color 

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

games.screen.mainloop() 

回答

2

這是一個非常簡單的問題,你需要處理「跳槽」事件,看到事件文檔:http://www.pygame.org/docs/ref/event.html

編輯: 現在發生,我認爲你可能會處理「 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() 
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. 
2

在使用pygame時,你必須處理包括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

我推薦下面的代碼。首先,它包含Clock,所以你的程序不會吃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() 
+0

使用此效果最好。一旦做錯,您可以輕鬆保存任何狀態。 – ninMonkey 2012-11-22 21:31:53

1

爲了使pygame的窗口關閉的簡單,使得與功能while True:那麼遊戲循環在此使用功能for event in pygame.event.get():創建一個for循環,接下來添加的代碼if event.type == QUIT:如果你已經創建了一個「而True'循環你只需要添加最後一段代碼。現在添加在pygame.quit()sys.exit(),這裏是成品代碼:

while True: 
for event in pygame.event.get(): 
    if event.type == QUIT: 
     pygame.quit() 
     sys.exit() 

請注意,你需要有第一進口pygame的和sys。