1

我一直在尝试让我的代码收集按下哪个鼠标按钮及其位置,但是每当我运行以下代码时,pygame 窗口都会冻结,并且外壳/代码会继续输出鼠标的起始位置。有谁知道为什么会发生这种情况,更重要的是如何解决它? (对于下面的代码,我使用了这个网站https://www.pygame.org/docs/ref/mouse.html和其他堆栈溢出答案,但它们对我的问题还不够具体。)

clock = pygame.time.Clock()
# Set the height and width of the screen
screen = pygame.display.set_mode([700,400])

pygame.display.set_caption("Operation Crustacean")


while True:
    clock.tick(1)
    screen.fill(background_colour)

    click=pygame.mouse.get_pressed()
    mousex,mousey=pygame.mouse.get_pos()

    print(click)
    print(mousex,mousey)
    pygame.display.flip()
4

1 回答 1

1

您必须pygame.event定期调用其中一个函数(例如pygame.event.pumpor for event in pygame.event.get():),否则pygame.mouse.get_pressed(和一些操纵杆函数)将无法正常工作,并且 pygame 窗口将在一段时间后变得无响应。

这是一个可运行的示例:

import pygame


pygame.init()
screen = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()
BG_COLOR = pygame.Color('gray12')

done = False
while not done:
    # This event loop empties the event queue each frame.
    for event in pygame.event.get():
        # Quit by pressing the X button of the window.
        if event.type == pygame.QUIT:
            done = True
        elif event.type == pygame.MOUSEBUTTONDOWN:
            # MOUSEBUTTONDOWN events have a pos and a button attribute
            # which you can use as well. This will be printed once per
            # event / mouse click.
            print('In the event loop:', event.pos, event.button)

    # Instead of the event loop above you could also call pygame.event.pump
    # each frame to prevent the window from freezing. Comment it out to check it.
    # pygame.event.pump()

    click = pygame.mouse.get_pressed()
    mousex, mousey = pygame.mouse.get_pos()
    print(click, mousex, mousey)

    screen.fill(BG_COLOR)
    pygame.display.flip()
    clock.tick(60)  # Limit the frame rate to 60 FPS.
于 2018-11-10T11:55:05.520 回答