Python中的载入栏崩溃

时间:2018-07-18 14:28:34

标签: python pygame

我和我的熟人正在创建一个加载条,需要花费很多时间才能获得乐趣。但是,制作此加载条时,它似乎在前一两秒内崩溃。这是代码:

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)

对代码的任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

您的问题是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)以便在函数中缩进

答案 1 :(得分:0)

有两件事需要更改:

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

  2. 您必须删除time.sleep调用,因为它阻止了该程序,因此无法处理事件,并且窗口也将冻结(在指定的时间内)。

我不确定您要使用time.sleep来实现什么,但是最有可能是一种更好的方法。