Reputation: 43
The following code is to create a button which would change color if the cursor hovered over it while ends the program, if it is clicked upon. The result does not show the buttons but only the background. I have image of the pygame window after execution at the bottom. '''
# initialising
import pygame, sys
pygame.init()
HEIGHT = 720
WIDTH = 720
screen = pygame.display.set_mode((HEIGHT,WIDTH))
# colour
WHITE = (255,255,255)
BLACK = (0, 0 ,0 )
MAROON = (128,0 ,0 )
RED = (255,0 ,0 )
x, y = pygame.mouse.get_pos()
# rendering a text written in
# this font
# defining a font
smallfont = pygame.font.SysFont('Corbel',35)
text = smallfont.render('quit' , True , BLACK)
# superimposing the text onto our button
screen.blit(text,(WIDTH/2 +50, HEIGHT/2))
# describing the process
while True:
for ev in pygame.event.get():
if ev.type == pygame.QUIT:
pygame.quit()
#describing events
if ev.type == pygame.MOUSEBUTTONDOWN:
if WIDTH/2 -70 <= x <= WIDTH/2 + 70 and HEIGHT/2 -70 <= x <= HEIGHT/2 + 70:
pygame.quit()
pygame.display.flip()
if WIDTH/2 -70 <= x <= WIDTH/2 + 70 and HEIGHT/2 -70 <= x <= HEIGHT/2 + 70:
pygame.draw.rect(screen,RED,(100,100,500,500))
else:
pygame.draw.rect(screen,MAROON,(100,100,500,500))
# filling screen with colour
screen.fill(WHITE)
# updates the frames of the game
pygame.display.update()
I have tried pygame.display.flip(), changing positions of the rectangles but the issue is not resolved.
I am a beginner in pygame and hence just starting.
Upvotes: 2
Views: 46
Reputation: 211249
You have to draw the rectangles before screen.fill(WHITE)
. Note pygame.Surface.fill
filles the entire Surface with a solid color. Everything what is drawn before is covered.
# describing the process
while True:
# [...]
# filling screen with colour
screen.fill(WHITE)
if WIDTH/2 -70 <= x <= WIDTH/2 + 70 and HEIGHT/2 -70 <= x <= HEIGHT/2 + 70:
pygame.draw.rect(screen,RED,(100,100,500,500))
else:
pygame.draw.rect(screen,MAROON,(100,100,500,500))
# updates the frames of the game
pygame.display.update()
Upvotes: 2