gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 00:44:03 24 4
gpt4 key购买 nike

我正在尝试在 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"

最佳答案

使用 pygame.Rect要定义区域,请检查鼠标按钮是否在事件循环中按下,并使用 area 矩形的 collidepoint 方法查看它是否与 事件发生碰撞.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()

关于python - 如何检查鼠标是否在某个区域被点击(pygame),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44998943/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com