2013-04-29 65 views
4

我不能得到一個非常簡單的pygame的腳本工作:pygame的mouse.get_pos()不工作

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

這只是輸出(0,0),因爲我移動鼠標在窗口:

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

任何人都可以檢查嗎?

編輯 - 固定代碼:

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

回答

4

pygame的會經常調度的事件,而它的運行。這些需要以某種方式處理,否則pygame會掛起而不做任何事情。要解決這個問題最簡單的方法是添加給你的主循環:

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

'a = 0'不會「什麼也不做」。使用'通過'... – kindall 2013-04-29 19:32:40

+0

正式指出,並表示感謝。順便下次你可以編輯答案。 ;) – 2013-04-29 19:39:01

+0

我總是忘了! – kindall 2013-04-29 19:47:00

1

我從來沒有使用過這一點,但我發現,

Pygame: Mouse Specific Axis Detection

你需要等待,直到事件發生。我假設這會清空堆棧並允許您稍後獲取數據。

for event in pygame.event.get()