如何检查某个区域是否单击了鼠标(pygame)

时间:2017-07-09 17:07:44

标签: python pygame

我正在尝试在pygame中创建一个程序,如果在某个区域按下鼠标,它将打印一些东西。我尝试过使用mouse.get_pos和mouse.get_pressed,但我不确定我是否正确使用它们。这是我的代码

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"

2 个答案:

答案 0 :(得分:1)

使用pygame.Rect定义区域,检查事件循环中是否按下了鼠标按钮,并使用collidepoint rect的area方法查看它是否与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()

答案 1 :(得分:0)

在我的游戏中,我使用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"