不知道起什么标题 03

最近对pygame感兴趣,在网上找了教程来学习(网址:http://eyehere.net/2011/python-pygame-novice-professional-index/),但当我把上面的代码复制到Python IDLE中运行时,却发现明明点击了游戏窗口的关闭按钮,但就是无法让其关闭,并且窗口就对我的操作毫无反应。

 

在研究了网上教程的代码后,发现问题出在退出代码上 

from sys import exit    #问题所在
......

#游戏主循环
while True:
    ......
    event = pygame.event.wait()
    if event.type == QUIT:
        exit()

教程代码中的from语句导入了sys模块的exit,sys.exit()与默认的exit()有着一定的区别(我以前一直以为它们是一个函数)。

#PythonShell的输出结果:默认的exit函数
>>> help(exit)
Help on Quitter in module _sitebuiltins object:

class Quitter(builtins.object)
 |  Methods defined here:
 |  
 |  __call__(self, code=None)
 |      Call self as a function.
 |  
 |  __init__(self, name, eof)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  
 |  __repr__(self)
 |      Return repr(self).
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)

#PythonShell的输出结果:sys.exit
>>> import sys
>>> help(sys.exit)
Help on built-in function exit in module sys:

exit(...)
    exit([status])
    
    Exit the interpreter by raising SystemExit(status).
    If the status is omitted or None, it defaults to zero (i.e., success).
    If the status is an integer, it will be used as the system exit status.
    If it is another kind of object, it will be printed and the system
    exit status will be one (i.e., failure).

可以看出,两个exit函数一个是来自“_sitebuiltins”模块,一个是来自“sys”模块。

回到问题本身,最后经过试验,我发现有三种解决办法:

  • 第一种方法是在exit方法前加一句pygame.quit(),以此释放掉占用的资源
  • 第二种方法是删除掉from语句,当点击关闭按钮时,会弹出对话框:

 

点击“确定”或“取消”后就能成功退出程序

  • 第三种方法是直接双击py文件运行,在这种情况下,无论exit函数是什么版本,都可以正常退出
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值