如何区分pygame中的鼠标左键单击和右键单击



从pygame的api来看,它有:

event type.MOUSEBUTTONDOWN, MOUSEBUTTONUP, MOUSEMOTION

但是没有办法区分左右点击?

点击事件


if event.type == pygame.MOUSEBUTTONDOWN:
    print(event.button)

event.button可以等于几个整数值:

1 - left click
2 - middle click
3 - right click
4 - scroll up
5 - scroll down

正在获取鼠标状态


不用等待事件,您还可以获得当前按钮状态:

state = pygame.mouse.get_pressed()

这返回一个形式为(leftclick, middleclick, rightclick) 的元组

每个值都是一个布尔整数,表示是否按下了该按钮。

您可能需要仔细阅读本教程,以及n.st对这个SO问题的回答。

因此,向您展示如何区分左右点击的代码如下所示:

#!/usr/bin/env python
import pygame
LEFT = 1
RIGHT = 3
running = 1
screen = pygame.display.set_mode((320, 200))
while running:
    event = pygame.event.poll()
    if event.type == pygame.QUIT:
        running = 0
    elif event.type == pygame.MOUSEBUTTONDOWN and event.button == LEFT:
        print "You pressed the left mouse button at (%d, %d)" % event.pos
    elif event.type == pygame.MOUSEBUTTONUP and event.button == LEFT:
        print "You released the left mouse button at (%d, %d)" % event.pos
    elif event.type == pygame.MOUSEBUTTONDOWN and event.button == RIGHT:
        print "You pressed the right mouse button at (%d, %d)" % event.pos
    elif event.type == pygame.MOUSEBUTTONUP and event.button == RIGHT:
        print "You released the right mouse button at (%d, %d)" % event.pos
    screen.fill((0, 0, 0))
    pygame.display.flip()

MOUSEBUTTONDOWN事件在单击鼠标按钮时发生一次,MOUSEBUTTONUP事件在释放鼠标按钮时出现一次。pygame.event.Event()对象有两个属性,它们提供有关鼠标事件的信息。每个鼠标按钮都关联一个值。例如,鼠标左键、鼠标中键、鼠标右键、鼠标滚轮向上和鼠标滚轮向下的属性值分别为1、2、3、4、5。当按下多个键时,会发生多个鼠标按钮事件。进一步的解释可以在模块pygame.event:的文档中找到

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        if event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1:
                print("left mouse button")
            elif event.button == 2:
                print("middle mouse button")
            elif event.button == 3:
                print("right mouse button")
            elif event.button == 4:
                print("mouse wheel up")
            elif event.button == 5:
                print("mouse wheel down")

或者可以使用CCD_ 7。pygame.mouse.get_pressed()返回布尔值列表​​其表示所有鼠标按钮的状态(TrueFalse)。只要按下按钮,按钮的状态就是True。当按下多个按钮时,列表中的多个项目为True。列表中的第1、第2和第3个元素表示鼠标左键、中键和右键。如果按下特定按钮,可以通过订阅进行评估:

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
    mouse_buttons = pygame.mouse.get_pressed()
    button_msg = ""
    if mouse_buttons[0]:
        button_msg += "left mouse button  "
    if mouse_buttons[1]:
        button_msg += "middle mouse button  "
    if mouse_buttons[2]:
        button_msg += "right mouse button  "
    if button_msg == "":
        print("no button pressed")
    else:
        print(button_msg)

相关内容

  • 没有找到相关文章

最新更新