Python,pygame鼠标的位置以及按下的按钮

时间:2018-11-10 11:28:55

标签: python pygame

我一直在尝试收集收集按下哪个鼠标按钮及其位置的代码,但是每当我运行以下代码时,pygame窗口就会冻结,而shell /代码将继续输出鼠标的起始位置。有谁知道为什么会这样,更重要的是如何解决呢? (对于下面的代码,我使用了该网站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()

1 个答案:

答案 0 :(得分:1)

您必须定期调用pygame.event函数之一(例如pygame.event.pumpfor 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.
相关问题