在pygame中单击图像时如何运行函数?

2024-09-27 00:16:40 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: rect图像imagetxteventifdisplayload
2条回答

检测鼠标单击,然后在单击发生时检查鼠标的位置,并使用collidepoint功能查看鼠标是否在图像中:

for event in pygame.event.get():
    if event.type == pygame.QUIT:
        done = True
    if event.type == pygame.MOUSEBUTTONDOWN:
        mousePos = pygame.mouse.get_pos()
        if Sexe.get_rect().collidepoint(mousePos):
            runFunction()

一般来说,你说的是使用一个按钮来执行一些事情。为此,我们需要知道玩家用鼠标点击的位置,测试它是否在描绘图像的区域(我们的“按钮”)内,如果是,执行一个函数。下面是一个小例子:

    # get the mouse clicks
    mouse = pygame.mouse.get_pos()   # position
    click = pygame.mouse.get_pressed()  # left/right click

    if img.x + img.width > mouse[0] > img.x and img.y + img.height > mouse[1] > img.y:  # Mouse coordinates checking.
         
         if click[0] == 1: # Left click
             my_function_on_click()

它要求图像对象具有xy坐标以及定义的heightwidth。如果您的图像对象有一个与您可以调用该rect的大小相同的rect,或者如另一个答案所指出的那样,使用collidepoint函数,则会容易得多

使用复制到注释中的代码的最小示例:

width = 48
height = 48
x = 100
y = 100

exe = pygame.image.load('exe.jpg')
Sexe = pygame.transform.scale(exe,(width,height))

 while not done: 
    screen.blit(Sexe,[x,y]) # blit image

    for event in pygame.event.get():        
        if event.type == pygame.QUIT: 
            done = True 

 
    mouse = pygame.mouse.get_pos() 
    position click = pygame.mouse.get_pressed() # left/right click 

    # Mouse coordinates checking:
    sexe_rect = Sexe.get_rect()
    if sexe_rect.x + sexe_rect.width > mouse[0] > sexe_rect.x and sexe_rect.y + sexe_rect.height > mouse[1] > sexe_rect.y: 
    # if Sexe.get_rect().collidepoint(mousePos): # Alternative, A LOT shorter and more understandable
     
        if click[0] == 1: # Left click 
            print("I GOT CLICKED!")

相关问题 更多 >

    热门问题