如何在pygame开始时设置光标的位置?

问题描述

我必须为学校项目编写一个 pygame 程序,但遇到了一些有关 mouse.set_pos 的问题。

我需要在程序开始时设置鼠标位置。这里我把它设置在我的小窗口的中间,但是每次运行它时,鼠标都没有设置在我的窗口中间......可能是因为它在while循环之外。

[...]

pygame.display.init()

running = True
positions = []
file_contents = {}
click_counter = 1

screen_y = 640
screen_x = 400
pygame.display.set_mode((screen_y,screen_x))
pygame.mouse.set_pos([screen_y / 2,screen_x / 2])

while running:
[...]

另一方面,当我尝试在 while 循环中使用 pygame.mouse.set_pos([screen_y / 2,screen_x / 2]) 时,我的光标总是停留在给定的位置。

如何使用 pygame.mouse.set_pos() 以便我只能在开始时设置鼠标位置?

解决方法

如果您不介意使用 pyautogui,这里有一个解决方案。

import pygame
import os
import pyautogui

winPos = 100
os.environ["SDL_VIDEO_WINDOW_POS"]= "{},{}".format(winPos,winPos)

pygame.display.init()

running = True
screen_y = 640
screen_x = 400
pygame.display.set_mode((screen_y,screen_x))
pyautogui.moveTo(winPos + screen_y / 2,winPos + screen_x / 2)

while running:
    pygame.event.get()