I have a simple project that display a “button” with an image,a text and a background color:
import os os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide" import pygame, sys from pygame.locals import * import requests import io BLACK = (0, 0, 0) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 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,0,200,200,"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,color=RED, 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, top, w, 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()
that’s works fine but the problem is that when i launch the game it load the main window, wait some time(something like 1 second) and then load the button.I tried to add more button and it loaded them one at a time.I don’t undestand why.
Advertisement
Answer
Two Fixes
- Use a local image rather than an image sent with requests
- It loads slowly maybe because of the draw function of the MainWindow class.
Try this in the main loop function
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()
And at the end
main = Main_window() main.mainLoop()
So you don’t have to call main.draw()
because it is already being called in the main loop.