I have a simple project that display a “button” with an image,a text and a background color:
JavaScript
x
72
72
1
import os
2
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide"
3
import pygame, sys
4
from pygame.locals import *
5
import requests
6
import io
7
8
BLACK = (0, 0, 0)
9
RED = (255, 0, 0)
10
GREEN = (0, 255, 0)
11
BLUE = (0, 0, 255)
12
GRAY = (200, 200, 200)
13
14
class Main_window:
15
def __init__(self):
16
pygame.init()
17
self.screen = pygame.display.set_mode((800, 600))
18
def draw(self):
19
Btn1 = Button(0,0,200,200,"hello",color=RED, text="test",text_color=BLACK)
20
def mainLoop(self):
21
done = False
22
while not done:
23
eventlist = pygame.event.get()
24
for ev in eventlist:
25
if ev.type == QUIT:
26
done = True
27
if ev.type == MOUSEBUTTONDOWN:
28
Button.getButton(ev)
29
pygame.quit()
30
31
class Button:
32
Buttons = []
33
34
def __init__(self, left, top, w, h,function,color=RED, text="", text_color = BLACK):
35
self.left = left
36
self.top = top
37
self.w = w
38
self.h = h
39
self.right = self.left+w
40
self.bottom = self.top+h
41
self.function = function
42
surf1 = pygame.Surface((w, h))
43
surf1.fill(color)
44
rect1 = pygame.Rect(left, top, w, h)
45
main.screen.blit(surf1, rect1)
46
Button.Buttons.append(self)
47
if text != "":
48
font1 = pygame.font.SysFont('chalkduster.ttf', 72)
49
text1 = font1.render(text, True, text_color)
50
text_rect = text1.get_rect(center=(int(w/2), int(h/2)))
51
main.screen.blit(text1, text_rect)
52
image_url = "https://image.flaticon.com/icons/png/512/31/31990.png"
53
r = requests.get(image_url)
54
img = io.BytesIO(r.content)
55
image = pygame.image.load(img)
56
image = pygame.transform.scale(image, (w, h))
57
main.screen.blit(image, (0, 0))
58
pygame.display.flip()
59
60
def getButton(event):
61
for i in Button.Buttons:
62
x, y = event.pos
63
if x>=i.left and x<=i.right and y<=i.bottom and y>=i.top:
64
eval(i.function+"()")
65
66
def hello():
67
print("hello")
68
69
main = Main_window()
70
main.draw()
71
main.mainLoop()
72
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
JavaScript
1
13
13
1
def mainLoop(self):
2
done = False
3
while not done:
4
eventlist = pygame.event.get()
5
for ev in eventlist:
6
if ev.type == QUIT:
7
done = True
8
if ev.type == MOUSEBUTTONDOWN:
9
Button.getButton(ev)
10
self.draw()
11
pygame.display.flip()
12
pygame.quit()
13
And at the end
JavaScript
1
3
1
main = Main_window()
2
main.mainLoop()
3
So you don’t have to call main.draw()
because it is already being called in the main loop.