繁体   English   中英

Python Pygame窗口无响应

[英]Python Pygame Window Not Responding

我试图在pygame(一个Python模块)的帮助下用Python 3.6编写程序,该程序应该在屏幕上快速闪烁红色,绿色和蓝色。 该程序将按预期运行约十到十五秒,然后再停止响应。 (我注意到,控制台上只打印了3个事件,而应该再增加3个。)

import pygame
import threading
import time

'''
IMPORTS ARE ABOVE THIS LINE
'''


class EventHandler(threading.Thread):

    def run(self):
        for event in pygame.event.get():
            print(event)
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()


'''
CLASSES ARE ABOVE THIS LINE
'''


# Initializer
gameInit = pygame.init()

# Colors
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)

# Setup Crap
gameDisplay = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Pygame Colors")

# Event Handler
handler = EventHandler()
handler.start()

 # Game Loop
while True:
    gameDisplay.fill(red)
    pygame.display.update()
    time.sleep(0.1)
    gameDisplay.fill(green)
    pygame.display.update()
    time.sleep(0.1)
    gameDisplay.fill(blue)
    pygame.display.update()
    time.sleep(0.1)

您需要在run方法中使用while循环,并将主循环放入函数中。

import pygame
import threading
import time


class EventHandler(threading.Thread):

    def run(self):
        while True:
            for event in pygame.event.get():
                print(event)
                if event.type == pygame.QUIT:
                    pygame.quit()
                    quit()

gameInit = pygame.init()

red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)

gameDisplay = pygame.display.set_mode((800, 600))

def main_loop():
    while True:
        gameDisplay.fill(red)
        pygame.display.update()
        time.sleep(0.4)
        gameDisplay.fill(green)
        pygame.display.update()
        time.sleep(0.4)
        gameDisplay.fill(blue)
        pygame.display.update()
        time.sleep(0.4)

handler = EventHandler()
handler.start()
t = threading.Thread(target=main_loop)
t.start()

但是,在这种情况下,实际上不需要threading ,并且代码对我来说似乎很奇怪。 您可以只使用pygame.time.get_ticks()计算经过的时间,然后在超出时间限制时更改颜色。 如果要无限循环几个值, itertools.cycle非常方便。

import itertools

import pygame


pygame.init()

red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
# An infinite iterator that cycles through these colors.
colors = itertools.cycle((red, green, blue))
color = next(colors)

gameDisplay = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock()
start_time = 0

done = False

while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

    current_time = pygame.time.get_ticks()
    if current_time - start_time > 500:  # 500 milliseconds.
        color = next(colors)
        start_time = current_time

    gameDisplay.fill(color)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

我建议您的代码运行速度太快,并增加time.sleep值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM