我正在尝试让python检测鼠标的位置。我的代码:
import pygames
pygame.init()
size = (700, 500)
screen = pygame.display.set_mode(size)
WHITE = (255,255,255)
screen.fill(WHITE)
pygame.mouse.set_pos([100,100]) #I didn't move my mouse so [0,100] should be the output
x_y = pygame.mouse.get_pos()
#I then run this program. Here is the output:
(0, 0)
我不知道出了什么问题。为什么坐标错了?
答案 0 :(得分:1)
我不知道它为什么显示错误的坐标,但它似乎只发生在pygame窗口前面有另一个窗口(在本例中为IDLE窗口)。如果选择/聚焦pygame窗口并设置鼠标pos,pygame.mouse.get_pos()
将返回正确的坐标。尝试在事件循环中设置鼠标位置(按 s 键):
import pygame
pygame.init()
size = (800, 500)
screen = pygame.display.set_mode(size)
pygame.mouse.set_pos([100,100])
WHITE = (255,255,255)
clock = pygame.time.Clock()
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_s:
pygame.mouse.set_pos([100,100])
print(pygame.mouse.get_pos())
screen.fill(WHITE)
pygame.display.flip()
clock.tick(30)
pygame.quit()
或者在命令行/终端中运行程序。