Skip to main content
 首页 » 编程设计

python之pygame.mouse.get_pos() 不在 while 循环中更新位置

2024年11月24日13wuhuacong

我正在尝试在 python 中制作一个工具,它返回当前光标位置和先前的光标位置,但是当我运行这段代码时,cur 始终与初始化代码时相同。我试着按住光标并四处移动它,但没有什么会使 cur 发生变化。

import pygame 
pygame.init() 
gameDisplay = pygame.display.set_mode((400, 400)) 
white = (255, 255, 255) 
gameDisplay.fill(white) 
pygame.display.update() 
event = True 
cur = pygame.mouse.get_pos() 
curList = [] 
while event: 
    cur = pygame.mouse.get_pos() 
    curList.append(cur) 
    if len(curList) >= 2: 
        curList.pop(0) 
    print(curList) 

请您参考如下方法:

OP 的代码有几个问题。对于初学者来说,它不处理事件队列,所以(可能)这就是你没有获得鼠标更新的原因。它还允许您干净地退出程序。

import pygame 
pygame.init() 
gameDisplay = pygame.display.set_mode((400, 400)) 
white = (255, 255, 255) 
 
curList = [ (0,0) ] 
done = False 
 
while not done: 
    # paint the screen 
    gameDisplay.fill(white) 
    pygame.display.update() 
 
    # handle user interaction, at least exiting the window 
    for event in pygame.event.get(): 
        if ( event.type == pygame.QUIT ): 
            done = True 
 
    cur = pygame.mouse.get_pos() 
    # Append a new mouse position, iff it's moved 
    if ( cur != curList[-1] ): 
        curList.append(cur) 
        if len(curList) >= 2: 
            curList.pop(0) 
        print(curList) 

我修改了点跟踪以仅在传入点与列表中的最后一个点不同时才更新列表。但是考虑到该列表无论如何都只是一个项目,所以这一切都没有实际意义。