[英]Python, pygame mouse position and which button is pressed
I have been trying to get my code collecting which mouse button is pressed and its position yet whenever I run the below code the pygame window freezes and the shell/code keeps outputting the starting position of the mouse.我一直在尝试让我的代码收集按下了哪个鼠标按钮及其位置,但是每当我运行以下代码时,pygame 窗口都会冻结并且 shell/代码不断输出鼠标的起始位置。 Does anybody know why this happens and more importantly how to fix it?
有谁知道为什么会发生这种情况,更重要的是如何解决它? (For the code below I used this website https://www.pygame.org/docs/ref/mouse.html and other stack overflow answers yet they were not specific enough for my problem.)
(对于下面的代码,我使用了这个网站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()
You have to call one of the pygame.event
functions regularly (for example pygame.event.pump
or for event in pygame.event.get():
), otherwise pygame.mouse.get_pressed
(and some joystick functions) won't work correctly and the pygame window will become unresponsive after a while.您必须定期调用
pygame.event
函数之一(例如pygame.event.pump
或for event in pygame.event.get():
),否则pygame.mouse.get_pressed
(和一些操纵杆函数)将无法工作正确,一段时间后 pygame 窗口将变得无响应。
Here's a runnable example:这是一个可运行的示例:
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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.