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

时间:2020-08-13 09:21:39

标签: python pygame

在pygame中单击图像时,如何运行函数?在我的程序中,当您单击某个图像时,我想运行特定功能。问题是,我不知道该怎么做。甚至有可能做到这一点?这是我的下面的代码...

import numpy as np
import pandas as pd
import statsmodels.api as sm

# Assume y is n by m where m is 1,000,000, use 1,000 here for speed
y = pd.DataFrame(np.random.standard_normal((20,1000)))
x = pd.DataFrame(sm.add_constant(np.random.standard_normal((20,3))))
_x = np.asarray(x)
_y = np.asarray(y)
b = np.linalg.lstsq(_x, _y, rcond=None)[0]
e = _y - _x @ b
err_var = (e**2).mean(0)
# correct formula depends if x has a constant, here I assume it does
r2 = 1.0 - err_var / ((_y - _y.mean(0))**2).mean(0)
xpxi = np.linalg.inv(_x.T@_x)
se = np.sqrt(np.diag(xpxi)[:,None]*err_var)
tstats = b / se

2 个答案:

答案 0 :(得分:1)

检测一次鼠标单击,然后在发生单击时检查鼠标的位置,并通过使用碰撞点功能查看它是否在图像内:

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

答案 1 :(得分:0)

通常,您谈到使用按钮执行某事。为此,我们需要知道玩家用鼠标单击的位置,测试它是否在描绘图像的区域(我们的“按钮”)之内,如果是,则执行一个功能。这是一个小例子:

    # 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!")