问题描述
for event in pygame.event.get():
if event.type==QUIT:
running=False
elif event.type == pygame.MOUSEBUTTONDOWN:
mouse_x,mouse_y = event.pos
我使用 mouse_x
和 mouse_y
进行绘图,但它们总是在变化。那么,如何在 pygame
中获取屏幕上每次点击的准确位置并使用它们进行绘制?
谢谢
解决方法
1.获取鼠标点击时的位置
当您开始按下按钮时,您可以使用 pygame.event.get()
获取精确帧的位置:
import pygame
from pygame.locals import * # import constants like MOUSEBUTTONDOWN
pygame.init()
screen = pygame.display.set_mode((640,480))
running = True
while running:
for event in pygame.event.get():
if event.type == QUIT:
running = False
elif event.type == MOUSEBUTTONDOWN and event.button = 0: # detect only left clicks
print(event.pos)
pygame.display.flip()
pygame.quit()
exit()
2.获取每一帧的位置
在这种情况下,您可以像这样使用 pygame.mouse.get_pos()
:
import pygame
from pygame.locals import * # import constants like MOUSEBUTTONDOWN
pygame.init()
screen = pygame.display.set_mode((640,480))
running = True
while running:
for event in pygame.event.get():
if event.type == QUIT:
running = False
print(pygame.mouse.get_pos())
pygame.display.flip()
pygame.quit()
exit()
如果只想在按下左键时获取鼠标位置:
将行 print(pygame.mouse.get_pos())
放在 if pygame.mouse.get_pressed()[0]:
中:
...
if pygame.mouse.get_pressed()[0]: # if left button of the mouse pressed
print(pygame.mouse.get_pos())
...
,
这段代码实际上检测各种鼠标点击,如果你只想要左键点击,你可以把它添加到你的 if 语句中:
elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
你也没有以正确的方式获取坐标,你需要这样写:
mouse_x,mouse_y = pygame.mouse.get_pos()
如果您需要使用发生的所有点击,您需要将 x_mouse 和 y_mouse 存储到日志中,您可以这样做:
# This outside the pygame loop
mouse_clicks = []
# This inside the pygame loop
for event in pygame.event.get():
if event.type==QUIT:
running=False
elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
mouse_clicks.append(pygame.mouse.get_pos())
现在您有一个包含所有点击的所有 x,y 坐标的元组列表