Pygame加载缓慢

问题描述

我有一个简单的项目,显示一个带有图像、文本和背景颜色的“按钮”:

import os
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide"
import pygame,sys
from pygame.locals import *
import requests
import io

BLACK = (0,0)
RED = (255,0)
GREEN = (0,255,0)
BLUE = (0,255)
GRAY = (200,200,200)

class Main_window:
    def __init__(self):
        pygame.init()
        self.screen = pygame.display.set_mode((800,600))
    def draw(self):
        Btn1 = Button(0,"hello",color=RED,text="test",text_color=BLACK)
    def mainLoop(self):
        done = False
        while not done:
            eventlist = pygame.event.get()
            for ev in eventlist:
                if ev.type == QUIT:
                    done = True
                if ev.type == MOUSEBUTTONDOWN:
                    Button.getButton(ev)
        pygame.quit()

class Button:
    Buttons = []

    def __init__(self,left,top,w,h,function,text="",text_color = BLACK):
        self.left = left
        self.top = top
        self.w = w
        self.h = h
        self.right = self.left+w
        self.bottom = self.top+h
        self.function = function
        surf1 = pygame.Surface((w,h))
        surf1.fill(color)
        rect1 = pygame.Rect(left,h)
        main.screen.blit(surf1,rect1)
        Button.Buttons.append(self)
        if text != "":
            font1 = pygame.font.SysFont('chalkduster.ttf',72)
            text1 = font1.render(text,True,text_color)
            text_rect = text1.get_rect(center=(int(w/2),int(h/2)))
            main.screen.blit(text1,text_rect)
        image_url = "https://image.flaticon.com/icons/png/512/31/31990.png"
        r = requests.get(image_url)
        img = io.BytesIO(r.content)
        image = pygame.image.load(img)
        image = pygame.transform.scale(image,(w,h))
        main.screen.blit(image,(0,0))
        pygame.display.flip()

    def getButton(event):
        for i in Button.Buttons:
            x,y = event.pos
            if x>=i.left and x<=i.right and y<=i.bottom and y>=i.top:
                eval(i.function+"()")

def hello():
    print("hello")

main = Main_window()
main.draw()
main.mainLoop()

这很好用,但问题是当我启动游戏时它会加载主窗口,等待一段时间(大约 1 秒)然后加载按钮。我尝试添加更多按钮,它一次加载一个时间。我不明白为什么。

解决方法

两个修复

  1. 使用本地图片而不是随请求发送的图片
  2. 加载缓慢可能是因为 MainWindow 类的绘制功能。
    在主循环函数中试试这个
    def mainLoop(self):
        done = False
        while not done:
            eventlist = pygame.event.get()
            for ev in eventlist:
                if ev.type == QUIT:
                    done = True
                if ev.type == MOUSEBUTTONDOWN:
                    Button.getButton(ev)
            self.draw()
            pygame.display.flip()
        pygame.quit()

最后

main = Main_window()
main.mainLoop()

因此您不必调用 main.draw(),因为它已经在主循环中被调用了。