Python 3.5.2:Pygame 鼠标悬停在矩形上时突出显示

Python 3.5.2: Pygame hightlight rectangle if mouse on it

使用pygame模块,我在屏幕上画了一个黑色的矩形。我写了一个代码,当我将鼠标悬停在它上面时,通过在它周围绘制另一个(绿色)矩形(宽度 = 4)来 "highlights" 我的矩形。 它有效,但前提是鼠标在其上移动。如果它静止在黑色矩形的表面上,则绿色矩形不会出现。 这是我的代码:

import random, pygame, sys
from pygame.locals import *

pygame.init()
done = False
clock = pygame.time.Clock()
white = (255,255,255) # COLLORS
black = (0,0,0)
red = (255,0,0)
green = (0,100,0)
display_width = 800 # SCREEN DIMMENSION
display_height = 600
game_display = pygame.display.set_mode((display_width,display_height)) # SCREEN

def draw_rect(x,y):
    rect = pygame.Rect(x, y, 40, 40)
    pygame.draw.rect(game_display, black, rect)
    if rect.collidepoint(mousex,mousey):
           box_hightlight(x,y)
def box_hightlight(x,y):
    pygame.draw.rect(game_display,green,(x-5,y-5,50,50),4)

while done != True:

    x = (display_width - 40) / 2
    y = (display_height - 40) / 2

    mousex = 0  # used to store x coordinate of mouse event
    mousey = 0 # used to store y coordinate of mouse event

    for event in pygame.event.get():  # PRESSED KEYS EFFECTS
        if event.type == pygame.QUIT:
            done = True
        elif event.type == MOUSEMOTION :
            mousex, mousey = event.pos
        elif event.type == MOUSEBUTTONUP:
            mousex, mousey = event.pos
            mouseClicked = True

    game_display.fill(white)
    draw_rect(x,y)
    pygame.display.update()
    clock.tick(60)

我错过了什么?

draw_rect 中,您检查位置 mousex, mousey 是否在 rect 内。

但是在您的主循环中,您将 mousex, mousey 设置为 0, 0,并且仅当 MOUSEMOTION(或 MOUSEBUTTONUP)事件发生时才将其设置为鼠标位置。

这解释了您的它有效,但前提是鼠标移过它 问题。

不要使用事件,只需使用 pygame.mouse.get_pos 获取鼠标位置。