矩形未在屏幕上绘制

时间:2020-07-20 15:36:21

标签: python pygame

下面的代码用于创建一个按钮,如果在单击该程序时将光标悬停在该按钮上,则该按钮将更改颜色。结果不显示按钮,而仅显示背景。 在底部执行后,我有pygame窗口的图像。 '''

# 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() 



        

我尝试了pygame.display.flip(),更改矩形的位置,但问题未解决。 我是pygame的初学者,因此才刚刚开始。 enter image description here

1 个答案:

答案 0 :(得分:2)

您必须在screen.fill(WHITE)之前绘制矩形。注意pygame.Surface.fill用纯色填充整个Surface。覆盖了之前绘制的所有内容。

# 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()