当鼠标光标悬停在我加载到屏幕上的图像时,我想打印一条语句,但只有当鼠标光标悬停在屏幕的左上部分时,即使图像位于右下角或中间位置,它才会打印出来。
import pygame, sys
from pygame import *
def main():
pygame.init()
FPS = 30
fpsClock = pygame.time.Clock()
screen = pygame.display.set_mode((600, 400))
cat = pygame.image.load('cat.png')
while True:
if cat.get_rect().collidepoint(pygame.mouse.get_pos()):
print "The mouse cursor is hovering over the cat"
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
screen.blit(cat, (300, 100))
pygame.display.flip()
fpsClock.tick(FPS)
main()发布于 2016-12-09 16:36:26
方法Surface.get_rect()返回与图像大小相同的矩形,但不是在同一位置!您将得到一个位于(0,0)的矩形,这就是当鼠标位于左上角时它会打印的原因。相反,您可以使用用于定位曲面的参数,并将它们传递给Surface.get_rect(x=300, y=100)方法。
或者更好的是,在加载图像的同时创建矩形。这样,您就不必创建一个新的矩形每个循环。然后,您可以根据rect定位您的图像:
import pygame, sys
from pygame import *
def main():
pygame.init()
FPS = 30
fpsClock = pygame.time.Clock()
screen = pygame.display.set_mode((600, 400))
cat = pygame.image.load('cat.png')
rect = cat.get_rect(x=300, y=100) # Create rectangle the same size as 'cat.png'.
while True:
if rect.collidepoint(pygame.mouse.get_pos()):
print "The mouse cursor is hovering over the cat"
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
screen.blit(cat, rect) # Use your rect to position the cat.
pygame.display.flip()
fpsClock.tick(FPS)
main()https://stackoverflow.com/questions/41064365
复制相似问题