在pygame中单击图像时,如何运行函数?在我的程序中,我想在单击某个图像时运行一个特定的函数。问题是,我不知道怎么做。甚至有可能做到这一点吗?下面是我的代码
import pygame
black = (0, 0, 0)
white = (255, 255, 255)
green = (0, 255, 0)
red = (255, 0, 0)
pygame.init()
size = (500, 400)
screen = pygame.display.set_mode(size)
pygame.draw.rect(screen, red,(150,450,100,50))
button1 = pygame.Rect(100,100,50,50)
button2 = pygame.Rect(200,200,50,50)
button3 = pygame.Rect(130,250,50,50)
pygame.display.set_caption("Yami no Game")
txt = pygame.image.load('txt.png')
Stxt = pygame.transform.scale(txt,(48,48))
exe = pygame.image.load('exe.jpg')
Sexe = pygame.transform.scale(exe,(48,48))
done = False
clock = pygame.time.Clock()
background_image=pygame.image.load('windows_background.jpg').convert()
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.MOUSEBUTTONDOWN:
100, 100 = event.pos
if Sexe.get_rect().collidepoint(100,100):
print('Runnig thing')
screen.blit(background_image, [0,0])
screen.blit(Stxt,[100,100])
screen.blit(Sexe,[250,250])
pygame.display.update()
clock.tick(60)
pygame.quit()
检测鼠标单击,然后在单击发生时检查鼠标的位置,并使用collidepoint功能查看鼠标是否在图像中:
一般来说,你说的是使用一个按钮来执行一些事情。为此,我们需要知道玩家用鼠标点击的位置,测试它是否在描绘图像的区域(我们的“按钮”)内,如果是,执行一个函数。下面是一个小例子:
它要求图像对象具有
x
和y
坐标以及定义的height
和width
。如果您的图像对象有一个与您可以调用该rect的大小相同的rect,或者如另一个答案所指出的那样,使用collidepoint
函数,则会容易得多使用复制到注释中的代码的最小示例:
相关问题 更多 >
编程相关推荐