简体   繁体   English

如何使用pygame鼠标单击来暂停循环?

[英]How to pause a loop with a mouse click using pygame?

I ma beginner in python and I m doing a project using pygame. 我是python的初学者,我正在使用pygame做一个项目。 I initiated a loop on a mouse click and it runs good. 我在单击鼠标时启动了一个循环,它运行良好。 But i couldn't stop that loop. 但是我无法停止那个循环。 I want it to stop on a mouse click and the loop should run until that mouse click. 我希望它在单击鼠标时停止,并且循环应该一直运行到单击鼠标为止。 I have provided the outline of the code, below. 我在下面提供了代码的概述。 Can anyone help me with a proper code? 任何人都可以通过正确的代码帮助我吗? Thanks in advance. 提前致谢。

for event in pygame.event.get():
    if (event.type == pygame.MOUSEBUTTONDOWN):
         (mx,my)= pygame.mouse.get_pos()
         if((mx>=375)&(mx<=425)&(my>=500)&(my<=550)): #to begin loop on mouse click#
           while True:
              ---statements-----
              if((mx>=300)&(mx<=350)&(my>=500)&(my<=550)): #to end loop on mouse click#
                 exit
              else:
                 continue

The problem is that once you enter the while True loop, you are no longer waiting for mouse events coming from pygame. 问题在于,一旦进入while True循环,您就不再等待pygame发出的鼠标事件。 Try checking for new events right before looping: 尝试在循环之前检查新事件:

for event in pygame.event.get(pygame.MOUSEBUTTONDOWN):
    mx, my = pygame.mouse.get_pos()
    if 375 <= mx <= 425 and 500 <= my <= 550:
        run = True
        while run:
            # statements
            # ...
            for event in pygame.event.get(pygame.MOUSEBUTTONDOWN):
                mx, my = pygame.mouse.get_pos()
                if 300 <= mx <= 350 and 500 <= my <= 550:
                    run = False

You can filter directly the events in the event.get call. 您可以在event.get调用中直接过滤事件。

Note that I rewrote the boundary checks, as the logic and in Python is actualy and , while & is a bitwise operation. 请注意,我重写了边界检查,因为逻辑和在Python中实际上是 ,而是按位运算。 Python allows for a cool syntax when checking ranges too! 检查范围时,Python也允许使用很酷的语法!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM