python - 如何使用 PySDL2 获取鼠标位置?

标签 python sdl pysdl2

除了监听事件之外,完全不明白如何实现获取鼠标位置,但是在事件队列为空的情况下,这是如何实现的?

pysdl for pygamers 的文档建议使用 sdl2.mouse.SDL_GetMouseState() ( doc here ) 但此函数实际上需要您想询问的光标的 x、y 坐标。同时,调用 sdl2.mouse.SDL_GetCursor() 返回一个光标对象,但我找不到从中获取其坐标的方法(即它只是包装了一个 C 对象,所以它有一个空的 .__dict__ 属性)。

我一直在尝试我能想到的一切,但我以前从未用 C 编程过。我试图生成的简单包装函数只是:

def mouse_pos(self):
            #  ideally, just return <some.path.to.mouse_x_y> 
            event_queue = sdl2.SDL_PumpEvents()
            state = sdl2.mouse.SDL_GetMouseState(None, None)  # just returns 0, so I tried the next few lines
            print state
            for event in event_queue:
                if event.type == sdl2.SDL_MOUSEMOTION:
            #  this works, except if the mouse hasn't moved yet, in which case it's none        
            return [event.x, event.y] 

最佳答案

SDL_GetMouseState() 是 SDL2 C 函数的包装器。因此,您必须使用 ctypes 从中检索值。原始SDL2函数接收两个指针(x和y)来存储光标位置。

下面的代码片段将为您做正确的事情:

import ctypes
...
x, y = ctypes.c_int(0), ctypes.c_int(0) # Create two ctypes values
# Pass x and y as references (pointers) to SDL_GetMouseState()
buttonstate = sdl2.mouse.SDL_GetMouseState(ctypes.byref(x), ctypes.byref(y))
# Print x and y as "native" ctypes values
print(x, y)
# Print x and y as Python values
print(x.value, y.value)

`

关于python - 如何使用 PySDL2 获取鼠标位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27322219/

相关文章:

python - 应用程序引擎中的 fetch() 与 run() 有何不同?

c++ - 当前路径/SDL 库

python - 如何确保使用 Python (pysdl2) 准备好 SDL2 全屏窗口?

python - Torrent Tracker 信息哈希 GET 请求 - Python

python - 如何将(快速更新的)变量从 ctypes C 代码传递给 Python?通过引用传递?

python - 将 VSCode 更新到 1.56.1 后,出现错误 : "Cannot activate the ' Python' extension because it depends on the 'Jupyter' extension. .."

c - 使用某些浏览器的网络应用程序出现问题

c++ - SDL: Blitting BMP to window surface 黑屏之谜

python - Pysdl2 卡在教程中

python - Cython + ctypes?