简体   繁体   English

pygame mouse.get_pos()不起作用

[英]pygame mouse.get_pos() not working

I can't get a very simple pygame script to work: 我无法获得一个非常简单的pygame脚本来工作:

import pygame

class MainWindow(object):

    def __init__(self):
        pygame.init()

        pygame.display.set_caption('Game')
        pygame.mouse.set_visible(True)
        # pygame.mouse.set_visible(False) # this doesn't work either!

        screen = pygame.display.set_mode((640,480), 0, 32)

        pygame.mixer.init()

        while True:
            print pygame.mouse.get_pos()

        pygame.mixer.quit()
        pygame.quit()

MainWindow()

This just outputs (0,0) as I move the mouse around the window: 当我在窗口上移动鼠标时,这只是输出(0,0):

(0, 0)
(0, 0)
(0, 0)
(0, 0)
(0, 0)

Can anyone check this? 有人可以检查吗?

Edit - fixed code: 编辑-固定代码:

import pygame

class MainWindow(object):

    def __init__(self):
        pygame.init()

        pygame.display.set_caption('Game')
        pygame.mouse.set_visible(True)
        # pygame.mouse.set_visible(False) # this doesn't work either!

        screen = pygame.display.set_mode((640,480), 0, 32)

        pygame.mixer.init()

        while True:
            for event in pygame.event.get():
                if event.type == pygame.MOUSEMOTION:
                    print pygame.mouse.get_pos()

        pygame.mixer.quit()
        pygame.quit()

MainWindow()

Pygame will constantly dispatch events while it's running. Pygame在运行时会不断调度事件。 These need to be handled in some way or pygame will hang and not do anything. 这些需要以某种方式处理,否则pygame会挂起并且不执行任何操作。 Simplest way to fix it is by adding this to your main loop: 解决此问题的最简单方法是将其添加到主循环中:

...
    while True:
        for event in pygame.event.get():
            pass                                             
        print pygame.mouse.get_pos()
...

I never used this before, but I found that 我以前从未用过,但是我发现

Pygame: Mouse Specific Axis Detection Pygame:鼠标特定轴检测

You need to wait until an event happens. 您需要等待事件发生。 I assume this empties the stack and allows you to get the data later on. 我认为这将清空堆栈,并允许您稍后再获取数据。

for event in pygame.event.get()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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