问题描述
编辑(已解决):使用event.button似乎可以解决问题。返回0、0、0时返回正确的鼠标按钮(1 =左,3 =右)
我已经尝试寻找解决方案,但是在每个答案中,似乎这个人都不知道或忘记将事件包含在pg.event.get()中。.pygame中的鼠标检测已停止可靠地工作而且我不确定这是否是硬件错误,我的代码是否错误或其他原因。这是我的鼠标游戏循环的简化版本:
while running:
for event in pg.event.get():
pos = pg.mouse.get_pos()
if event.type == pg.MOUSEBUTTONDOWN:
if grid_space.get_rect(x=(adj_x),y=(adj_y)).collidepoint(pos):
if pg.mouse.get_pressed()[2]:
do_thing()
elif event.button == 4:
do_thing()
elif event.button == 5:
do_thing()
else:
print(pg.mouse.get_pressed())
do_thing()
我将主鼠标按钮移到了else上,因为这是使最重要的操作此刻更可靠的唯一方法,但是通过打印else结果,我还发现每4或5次点击就会返回一次(0 ,0,0)而不是(1,0,0)。我尝试了多种表达方式,简化了结构,增加了Pygame的时钟,但没有任何效果。
有人遇到过这种情况吗?
edit:我已经运行了另一个测试,将get_pressed结果立即保存到变量中,并且它仍然返回0、0、0,所以我很确定它的状态没有从MOUESBUTTONDOWN更改为调用它的时间。
>解决方法
pygame.mouse.get_pressed()
获取鼠标按钮的当前状态。自从发生鼠标事件以来,按钮的状态可能已更改。请注意,事件存储在队列中,稍后您将在应用程序中通过pygame.event.get()
接收存储的事件。同时,按钮的状态可能已经更改,因为导致MOUSEBUTTONDOWN
事件的按钮被立即存储在pygame.event.Event
对象的button
属性中。在事件循环中,当您收到事件时,event.button
和pygame.mouse.get_pressed()
的状态可能不同。pygame.mouse.get_pos()
也是如此。鼠标的位置存储在属性pos
中
使用event.button
和event.pos
而不是pygame.mouse.get_pressed()
和pygame.mouse.get_pos()
:
while running:
for event in pg.event.get():
if event.type == pg.MOUSEBUTTONDOWN:
print(event.button)
if grid_space.get_rect(topleft=(adj_x,adj_y)).collidepoint(event.pos):
if event.button == 2:
do_thing()
elif event.button == 4:
do_thing()
elif event.button == 5:
do_thing()
else:
do_thing()
pygame.mouse.get_pos()
和pygame.mouse.get_pressed()
不能在事件循环中使用。这些功能应直接在应用程序循环中使用。