pygame检测鼠标光标在对象上

时间:2016-12-09 16:01:38

标签: python pygame

我想在鼠标光标悬停在我加载到屏幕上的图像上时打印一条语句,但只有当鼠标光标悬停在屏幕的左上部分时才会打印,即使图像位于屏幕的中央或底部右。

Public Sub GetData(SourceFile As Variant, SourceSheet As String, SourceRange As String, TargetRange As Range)
    Application.ScreenUpdating = False
    Dim CloseFile As Boolean
    Dim wb As Workbook
    On Error Resume Next
    Set wb = Workbooks(SourceFile)
    On Error GoTo 0
    If wb Is Nothing Then
        CloseFile = True
        Set wb = Workbooks.Open(Filename:=SourceFile, ReadOnly:=True)
    End If

    With wb
        With .Worksheets(SourceSheet)
            .Range(SourceRange).Copy
            TargetRange.PasteSpecial Paste:=xlPasteAll, Operation:=xlAdd, SkipBlanks:=False, Transpose:=False
        End With
        If CloseFile Then .Close SaveChanges:=False
    End With

    Application.ScreenUpdating = True
End Sub

1 个答案:

答案 0 :(得分:2)

方法Surface.get_rect()返回一个与图像大小相同但不在同一位置的矩形!您将得到一个位于(0,0)的矩形,这就是当鼠标位于左上角时打印的原因。你可以做的是取你用来定位曲面的参数并将它们传递给方法Surface.get_rect(x=300, y=100)

甚至更好,在加载图片的同时创建矩形。这样你就不必在每个循环中创建一个新的矩形。然后,您可以根据矩形定位图像:

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