python - 矩形未绘制在屏幕上

标签 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

最佳答案

您必须在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() 

关于python - 矩形未绘制在屏幕上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62998960/

相关文章:

python - Vim Flake8 忽略项目配置文件

python - 我可以使用另一个类的方法调用 python 对象的字典吗?

python - 我不知道在哪里调用函数。 pygame

python - 从 Python 将 TFRecord 输出到 Google Cloud Storage

python - 在 Excel 中设置 DataFrame 格式

python - ' bool 对象不可调用'pygame

python - 当我尝试运行代码时,Pygame 窗口没有响应错误

python - event_text[-SCREEN_SIZE[1]/font_height :]? 的说明

python - 复制像素区域

python - 从网页中提取表格