2013-03-05 87 views
2

在这里发表我的第一篇文章(或坦率地说,任何论坛),但我想知道为什么当窗口的退出按钮[x]被按下时,我不能退出。我曾尝试:点击退出pygame窗口

#print "Exit value ", pygame.QUIT 
for et in pygame.event.get(): 
    #print "Event type ", et.type 
    if et.type == pygame.KEYDOWN: 
      if (et.key == pygame.K_ESCAPE) or (et.type == pygame.QUIT): 
        print "In Here" 
        return True; 
pygame.event.pump()# not quite sure why we do this 
return False; 

我发现了pygame.QUIT打印12的值,因为我运行程序的事件类型打印“12”当我点击[X]。 “In here”字符串从不在这些场合打印。当返回为真时(当我按下键盘上的ESC)时,程序正常退出。我看了一些相关的问题:那么

我不是在怠速运转时,我上运行它:

的Eclipse朱诺服务与最新版本发布1
的Python 2.7.3 2.7(截至3/4/13)pygame。
的Windows 7 & 8和Ubuntu 12.04LTS

我已经在Windows 7中通过双击运行该程序,目前仍是.py文件运行(除了在Ubuntu无声卡错误相同的结果)不会对[X退出]。提前致谢。

回答

2

在你的事件循环,

#print "Exit value ", pygame.QUIT 
for et in pygame.event.get(): 
    #print "Event type ", et.type 
    #-----------------------------------------------------------------# 
    if et.type == pygame.KEYDOWN: 
      if (et.key == pygame.K_ESCAPE) or (et.type == pygame.QUIT): 
    #-----------------------------------------------------------------# 
        print "In Here" 
        return True; 
pygame.event.pump() # not quite sure why we do this 
return False; 

的问题(之间的2 #------------#
让我们来分析这一部分:

  1. 如果进入if区块,et.type == KEYDOWN
  2. 而你的支票QUITif et.type == KEYDOWN
  3. 由于et.typeKEYDOWN,它不能是QUIT ...
  4. 是这样,你不检查et.type == QUIT
    所以,你的窗户根本不会退出,即使你点击“X”。

怎么办?
拉你QUITKEYDOWN的条件,是这样的:

done = False 
while not done: 
    for event in pygame.event.get(): 
     if event.type == pygame.KEYDOWN: 
      if event.key == pygame.K_ESCAPE: 
       done = True 
       break # break out of the for loop 
     elif event.type == pygame.QUIT: 
      done = True 
      break # break out of the for loop 
    if done: 
     break # to break out of the while loop 

    # your game stuff 

注:

  • 您不需要这些return语句后;
  • 经常检查event.type在不同的if-elif块,如

    if event.type == pygame.QUIT: 
        #... 
    elif event.type == pygame.KEYDOWN: 
        #... 
    
  • 你不需要pygame.event.pump()那里,看到Here
+1

当然,谢谢你的观察! – SGM1 2013-03-05 17:32:39

0

主循环应该是这样的

done = False 
while not done: 
    for event in pygame.event.get(): 
     if event.type == KEYDOWN: 
      if event.key == K_ESCAPE: done = True 
     elif event.type == QUIT: 
      done = True 

    # draw etc... 
    pygame.display.update() 

然后,如果您切换“做”的任何地方,它会很好地退出。