简体   繁体   中英

pygame.mouse.get_pos() doesn't work (Python IDLE 3)

I'm trying to make python detect the position of the mouse. My code:

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)

I don't know what's wrong. Why are the coordinates wrong?

I don't know why it shows the wrong coordinates, but it seems to happen only if there's another window (in this case the IDLE window) in front of the pygame window. If the pygame window is selected/focussed and you set the mouse pos, pygame.mouse.get_pos() will return the correct coordinates. Try to set the mouse pos in an event loop (press the s key):

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()

Or run the program in the command-line/terminal.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM