如何检查鼠标是否在某个区域被点击(pygame)

2024-10-01 13:29:34 发布

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

我试图在pygame中制作一个程序,如果鼠标在某个区域被按下,它会打印出一些东西。我试过用mouse.get_pos以及鼠标。按下但我不确定我是否正确地使用了它们。这是我的密码

while True:
    DISPLAYSURF.fill(BLACK)
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            mpos = pygame.mouse.get_pos()
            mpress = pygame.mouse.get_pressed()
            if mpos[0] >= 400 and mpos[1] <= 600 and mpress == True:
                print "Switching Tab"

Tags: andpos程序eventtrue区域密码get
2条回答

使用^{}来定义区域,检查是否在事件循环中按下了鼠标按钮,并使用arearect的collidepoint方法来查看它是否与event.pos(或者pygame.mouse.get_pos())相冲突。在

import sys
import pygame as pg


def main():
    screen = pg.display.set_mode((640, 480))
    clock = pg.time.Clock()
    # A pygame.Rect to define the area.
    area = pg.Rect(100, 150, 200, 124)

    done = False

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True
            if event.type == pg.MOUSEBUTTONDOWN:
                if event.button == 1:  # Left mouse button.
                    # Check if the rect collides with the mouse pos.
                    if area.collidepoint(event.pos):
                        print('Area clicked.')

        screen.fill((30, 30, 30))
        pg.draw.rect(screen, (100, 200, 70), area)

        pg.display.flip()
        clock.tick(30)


if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()
    sys.exit()

在我的游戏中,我使用MOUSEBUTTONDOWN来检查鼠标按下:

while True:
    DISPLAYSURF.fill(BLACK)
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        (x, y)= pygame.mouse.get_pos()
        if x >= 400 and y <= 600 and event.type == pygame.MOUSEBUTTONDOWN:
            print "Switching Tab"

相关问题 更多 >