代码之家  ›  专栏  ›  技术社区  ›  CU12

pygame。老鼠get\u pos()不工作(Python IDLE 3)

  •  3
  • CU12  · 技术社区  · 7 年前

    我试图让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)
    

    我不知道怎么了。为什么坐标错误?

    1 回复  |  直到 7 年前
        1
  •  1
  •   skrx    7 年前

    我不知道为什么它显示了错误的坐标,但似乎只有在pygame窗口前面有另一个窗口(在本例中是空闲窗口)时才会发生这种情况。如果选择/聚焦pygame窗口并设置鼠标位置, 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()
    

    或在命令行/终端中运行程序。