Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/macos/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何检查鼠标是否在特定区域单击(pygame)_Python_Pygame - Fatal编程技术网

Python 如何检查鼠标是否在特定区域单击(pygame)

Python 如何检查鼠标是否在特定区域单击(pygame),python,pygame,Python,Pygame,我试图在pygame中制作一个程序,如果在某个区域按下鼠标,该程序将打印一些内容。我已尝试使用鼠标。点击鼠标位置和鼠标。点击鼠标,但我不确定是否正确使用它们。这是我的密码 while True: DISPLAYSURF.fill(BLACK) for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sy

我试图在pygame中制作一个程序,如果在某个区域按下鼠标,该程序将打印一些内容。我已尝试使用鼠标。点击鼠标位置和鼠标。点击鼠标,但我不确定是否正确使用它们。这是我的密码

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"
为True时:
DISPLAYSURF.fill(黑色)
对于pygame.event.get()中的事件:
如果event.type==退出:
pygame.quit()
sys.exit()
mpos=pygame.mouse.get_pos()
mpress=pygame.mouse.get_press()

如果mpos[0]>=400且mpos[1]在我的游戏中,我使用
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"
为True时:
DISPLAYSURF.fill(黑色)
对于pygame.event.get()中的事件:
如果event.type==退出:
pygame.quit()
sys.exit()
(x,y)=pygame.mouse.get_pos()
如果x>=400且y使用a定义区域,请检查是否在事件循环中按下了鼠标按钮,并使用
区域
rect的
碰撞点
方法查看它是否与
事件.pos
(或者
pygame.mouse.get_pos()
)发生碰撞


运行此代码时会发生什么情况?也许您应该实现一些调试代码来输出mpos[0]和mpos[1],并将mpress输出到屏幕或控制台,以便查看发生了什么。
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()