Python中的加载条崩溃

2024-05-03 14:36:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我和我的熟人正在努力创建一个加载条,需要永远加载的乐趣。然而,当制作这个加载杆时,它似乎会在头一两秒钟内崩溃。代码如下:

import pygame
import time
import random

pygame.init()

progress = 0

black = [0, 0, 0]
white = [255, 255, 255]
green = [0, 255, 0]

screenWidth = 600
screenHeigth = 800
size = [screenWidth, screenHeigth]

font = pygame.font.SysFont("Comic Sans MS", 25)

clock = pygame.time.Clock()

screen = pygame.display.set_mode(size)
pygame.display.set_caption('Loading...')


def textObjecte(text, color, size):
    if size == "small":
        textsuraface = font.render(text, True, color)

        return textsuraface, textsuraface.get_rect()


def loading(progress):
    if progress < 100:
        text = font.render("loading: " + str(int(progress)) + "%", True, green)

    screen.blit(text, (300, 100))


def message_to_screen(msg, color, y_displace, size="small"):
    textSurf, textRect = textObjecte(msg, color, size)
    textRect.center = (screenWidth/2), (screenHeigth/2) + y_displace

screen.blit(textSurf, textRect)


while progress/2 < 100:
    timeCount = random.randint(15, 30)
    increase = random.randint(1, 7)
    progress += increase
    screen.fill(black)
    pygame.draw.rect(screen, white, [300, 50, 200, 50])
    pygame.draw.rect(screen, black, [301, 51, 198, 48])

    if (progress/2) > 100:
        pygame.draw.rect(screen, white, [302, 52, 196, 46])
    else:
        pygame.draw.rect(screen, white, [302, 52, progress, 46])

    loading(progress/2)
    pygame.display.flip()

    time.sleep(timeCount)

任何代码方面的帮助都将不胜感激


Tags: textrectimportsizetimerandomscreenpygame
2条回答

有两件事需要改变:

  1. 您必须在每一帧处理事件(清空事件队列),否则窗口将变得无响应。调用^{}或添加事件循环for event in pygame.event.get():

  2. 必须删除time.sleep调用,因为它会阻塞程序,无法处理事件,窗口也会冻结(在指定的时间内)

我不确定您想用time.sleep实现什么,但很可能有更好的方法

你的问题是TextSurf是在一个函数中定义的,然后你试图在破坏它的函数之外使用它

def message_to_screen(msg, color, y_displace, size="small"):
    textSurf, textRect = textObjecte(msg, color, size)
    textRect.center = (screenWidth/2), (screenHeigth/2) + y_displace

screen.blit(textSurf, textRect)

您希望它缩进$ screen.blit(textSurf, textRect),以便它位于函数内部

相关问题 更多 >