0

我正在尝试使用 pythonw 运行 pygame 程序以避免显示控制台窗口。这会导致与打印语句相关的奇怪问题。

基本上,程序将在几秒钟后退出,没有错误消息。我打印的越多,它发生的越快。如果我在空闲或在命令提示符下(或在 linux 中)运行它,程序运行良好。此问题仅在使用 pythonw 启动时发生(右键单击、打开方式、pythonw)。

我在 Windows XP 32 位上使用 python 2.7.11。pygame 1.9.1 发布。

有解决方法吗?为什么程序简单地终止而没有错误?

import pygame
from pygame.locals import *

succeeded, failed = pygame.init()
display_surface = pygame.display.set_mode((320, 240))
clock = pygame.time.Clock()

terminate = False
while terminate is False:
    for event in pygame.event.get():
        if event.type == QUIT:
            terminate = True    
    area = display_surface.fill((0,100,0))
    pygame.display.flip()                 
    elapsed = clock.tick(20)              
    print str(elapsed)*20
pygame.quit()
4

1 回答 1

0

您不需要删除打印语句。保存它们以供以后调试。;-)

解决这个问题的两个步骤:

  • 首先,将所有代码保存在py文件中 - 不要将其更改为pyw现在;说是actualCode.py
  • 然后,创建一个runAs.pyw包含以下行的新文件
# In runAs.pyw file, we will first send stdout to StringIO so that it is not printed

import sys  # access to stdout
import StringIO  # StringIO implements a file like class without the need of disc

sys.stdout = StringIO.StringIO()  # sends stdout to StringIO (not printed anymore)

import actualCode  # or whatever the name of your file is, see further details below

请注意,仅导入actualCode 会运行该文件,因此,actualCode.py不应将执行的代码包含在我所说的is it main running file条件中。例如,

# In actualCode.py file
....
....
....
if __name__ == '__main__':  # Don't use this condition; it evaluates to false when imported
    ...  # These lines won't be executed when this file is imported,
    ...  # So, keep these lines outside
# Note: The file in your question, as it is, is fine
于 2017-08-28T05:29:19.837 回答