Skip to content
Advertisement

How can I set the position of my cursor at the start in pygame?

I have to write a pygame program for a school project and I run into some issues concerning mouse.set_pos.

I need to set the mouse position on the start of my program. Here I have set it to the middle of my little window, but everytime I run it, the mouse is not set to the middle of my window… probably because it is outside the while-loop.

[...]

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:
[...]

On the other hand, when I´m trying to use the pygame.mouse.set_pos([screen_y / 2, screen_x / 2]) inside of my while loop, my cursor is always stuck at the given position.

How do I use pygame.mouse.set_pos() in a way so I can only set the mouse position at the start?

Advertisement

Answer

Here is one solution if you don’t mind using 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()
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement