我正在尝试在 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"
Run Code Online (Sandbox Code Playgroud)
使用 apygame.Rect定义区域,在事件循环中检查鼠标按钮是否被按下,并使用rectcollidepoint的方法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()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6702 次 |
| 最近记录: |