当我在Pycharm上运行时,它打开后立即关闭。而在视频教程中它始终保持打开状态,为什么?
import pygame
pygame.init()
win = pygame.display.set_mode((500, 500))
pygame.display.set_caption("hello")
我正在使用Windows操作系统,python版本3.7.2和pygame 1.9.4
答案 0 :(得分:1)
I don't know which tutorial you talk about, but if the process that created the window finishes, the window will be closed.
E.g. when you create the window via a python shell, the window will stay open as long as the shell is open.
If you open the window via a script (a file), you need to keep the script from finishing. You do this by creating what is called a main loop and usually looks like this:
import pygame
def main():
pygame.init()
win = pygame.display.set_mode((500, 500))
pygame.display.set_caption("hello")
clock = pygame.time.Clock()
while True:
for e in pygame.event.get():
if e.type == pygame.QUIT:
return
win.fill((30, 30, 30))
pygame.display.update()
clock.tick(60)
if __name__ == '__main__':
main()
pygame.quit()
答案 1 :(得分:0)
我遇到了与您相同的问题(并且我遵循的是同一教程),我发现如果将整个内容括在while循环中(不包括 import pygame , pygame)。 init()和用于while循环的变量)效果很好。
import pygame
pygame.init()
Game = True
while Game is True:
window1 = pygame.display.set_mode((500, 500))
pygame.display.set_caption("First Game")
我刚刚开始学习Python,所以这可能不是最好的方法,但我希望它会有所帮助:)