Python 如何在不冻结窗口的情况下运行Pygame time.delay()?

Python 如何在不冻结窗口的情况下运行Pygame time.delay()?,python,python-3.x,pygame,Python,Python 3.x,Pygame,我在玩pygame时遇到了一些麻烦。我正在运行Mac High Sierra,使用Python 3,并使用Spyder作为编译器。我只是想运行一个简单的动画,但是time.delay()函数不起作用。每当我运行我的代码时,pygame窗口就会打开,保持灰色,直到时间延迟全部运行后才会填充白色。然后显示我的白色屏幕和圆圈的最终位置 如何在不冻结pygame窗口的情况下使time.delay函数正常运行 import pygame, sys pygame.init() screen = pyga

我在玩pygame时遇到了一些麻烦。我正在运行Mac High Sierra,使用Python 3,并使用Spyder作为编译器。我只是想运行一个简单的动画,但是time.delay()函数不起作用。每当我运行我的代码时,pygame窗口就会打开,保持灰色,直到时间延迟全部运行后才会填充白色。然后显示我的白色屏幕和圆圈的最终位置

如何在不冻结pygame窗口的情况下使time.delay函数正常运行

import pygame, sys

pygame.init()

screen = pygame.display.set_mode([640,480])
screen.fill([255,255,255])

pygame.draw.circle(screen, [255,0,255], [50,50],50, 0)
pygame.display.flip()

for x in range(5,640,5):
    pygame.time.wait(20)
    pygame.draw.rect(screen, [255,255,255],[x-5,0,100,100],0)
    pygame.draw.circle(screen, [255,0,255], [50+x,50],50, 0)
    pygame.display.flip()


while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

它在我的电脑上运行良好。所以很难说,但我相信问题在于代码的设计。通常,所有的绘图和动画都应该发生在主循环中(
而True
),不需要添加任何时间延迟

x = 0  # keep track of the x location
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    # clear the screen each time
    screen.fill([255, 255, 255])

    # draw the circle (notice the x variable wrapped in int())
    pygame.draw.circle(screen, [255, 0, 255], [int(50 + x), 50], 50, 0)

    # adjust higher or lower for faster animations
    x += 0.1

    # flip the display
    pygame.display.flip()
现在,动画与主循环同步。请记住,屏幕上的像素是以整数计算的,因此在绘制到屏幕上时,所做的任何浮点操作(例如
x+=0.1
)都需要是
int

如果您不想处理浮点数和小数,您可以将最小速度调整设置为1,但只能每一定帧数调整一次

x = 0  # keep track of the x location
frames = 0  # keep track of frames
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    # clear the screen each time
    screen.fill([255, 255, 255])

    # draw the circle (notice no int() function here)
    pygame.draw.circle(screen, [255, 0, 255], [50 + x, 50], 50, 0)

    # every 50 frames, increase movement. adjust higher or lower for varying speeds
    if frames % 50 == 0:
        x += 1  # never going to be a float, minimum of 1
    frames += 1

    # flip the display
    pygame.display.flip()

在事件驱动程序中使用延迟从来都不是一个好主意,因为程序需要与您的操作系统通信(解释)。您需要计算何时执行某些操作(如4位管理员在回答中所做的),或者使用事件(如所解释的)