[英]How to have pygame check when mouse is held down
So currently my code is 所以目前我的代码是
import pygame
def main():
pygame.init()
size = width, height = 800,700
backgroundColor = [0, 0, 255]
screen = pygame.display.set_mode(size)
screen.fill(backgroundColor)
pygame.display.flip()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
return
if pygame.mouse.get_pressed()[0]:
print event.pos
main()
What I am trying to do is that while the user is holding down the mouse, the position of the cursor is being recorded. 我正在尝试做的是,当用户按住鼠标时,正在记录光标的位置。 What I have works except when you click off the screen, and then click back on the screen, if gives the error:
我的工作原理是,除非您单击了屏幕,然后在屏幕上单击返回,如果出现错误:
line 23, in main print event.pos AttributeError: event member not defined
第23行,在主打印中event.pos AttributeError:未定义事件成员
How can I have get the same results as this code gives me, but when I click off the screen, and click back on, it wont give me an error? 如何获得与该代码给我的结果相同的结果,但是当我单击屏幕并再次单击时,它不会给我一个错误吗?
Just handle the exception: 只需处理异常:
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
return
if pygame.mouse.get_pressed()[0]:
try:
print event.pos
except AttributeError:
pass
If you print out the event
itself on each iteration, you'll see that you're getting an ActiveEvent
when you click onto the window, in addition to the normal MouseMotion
events: 如果您在每次迭代中都打印出
event
本身,那么除了正常的MouseMotion
事件外,您还可以看到单击窗口时会看到一个ActiveEvent
:
<Event(4-MouseMotion {'buttons': (0, 0, 0), 'pos': (703, 14), 'rel': (10, -12)})>
<Event(4-MouseMotion {'buttons': (0, 0, 0), 'pos': (714, 1), 'rel': (11, -13)})>
<Event(1-ActiveEvent {'state': 1, 'gain': 0})> # clicked off
<Event(1-ActiveEvent {'state': 1, 'gain': 1})> # clicked on
At the point you click back on, the mouse is pressed down, so you try processing the event, which throws an exception. 在您再次单击时,鼠标被按下,因此您尝试处理该事件,从而引发异常。 The easiest thing is to just catch that exception when it occurs.
最简单的方法是在发生异常时立即捕获该异常。 You could also check the event type to decide whether to try printing, too.
您也可以检查事件类型,以决定是否尝试打印。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.