【问题标题】:Python/Pygame mouse position not updating and program losing focusPython/Pygame 鼠标位置未更新且程序失去焦点
【发布时间】:2013-12-03 19:45:45
【问题描述】:

我正在尝试学习 Python/Pygame。我创建了一个将使用鼠标位置的程序,但是当我从 IDLE 和命令提示符运行它时,鼠标位置不会更新,当我单击图形窗口时,它会进入无响应模式。

代码非常简单(见下文)。发生的情况是打印命令一遍又一遍地打印原始鼠标位置。有什么想法吗?

import pygame
from pygame.locals import *
pygame.init()
Screen = pygame.display.set_mode([1000, 600])
MousePos = pygame.mouse.get_pos()
Contin = True
while Contin:
    print(MousePos)

【问题讨论】:

    标签: python mouseevent pygame mouse-position


    【解决方案1】:

    您没有将MousePos 更新为新值,而是一遍又一遍地打印出相同的值。 你需要的是:

    import pygame
    from pygame.locals import *
    pygame.init()
    Screen = pygame.display.set_mode([1000, 600])
    MousePos = pygame.mouse.get_pos()
    Contin = True
    while Contin:
        MousePos = pygame.mouse.get_pos()
        print(MousePos)
        DoSomething(MousePos)
    

    注意:如果您不处理任何其他事件,这也会进入非响应模式。

    这是处理 PyGame 中事件的更好方法:

    while running:
         event = pygame.event.poll()
         if event.type == pygame.QUIT:
             running = 0
         elif event.type == pygame.MOUSEMOTION:
             print "mouse at (%d, %d)" % event.pos
    

    【讨论】:

    • 非常感谢!没有看到 MousePos 未更新的错误,我感到很愚蠢……但是您的主管帮助似乎也解决了无响应的问题。非常感谢!!!
    【解决方案2】:

    将您的 while 循环更改为:

    while Contin:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                Contin = False
        MousePos = pygame.mouse.get_pos()
        print(MousePos)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-30
      • 1970-01-01
      • 2018-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-05
      • 1970-01-01
      相关资源
      最近更新 更多