在 Python 中,如何在 Macintosh 上的程序中执行函数时忽略 certain/all 按键

How to, in Python, ignore certain/all keypresses while function executing in program on Macintosh

我想知道,在 Python 中,我如何能够在程序中执行某个功能时忽略用户的 certain/all 按键操作?跨平台解决方案是首选,但如果那不可能,那么我需要知道如何在 Macintosh 上执行此操作。任何帮助是极大的赞赏! :)

编辑: 现在,我正在通过 turtle 模块的 onkey() 函数处理按键,因为我确实使用 turtle 创建了一个程序。我希望这有助于避免任何混淆,再次感谢您的帮助! :)

我发现了类似的问题,也许它会帮助你解决你的问题:

globally capture, ignore and send keyevents with python xlib, recognize fake input

How do I 'lock the keyboard' to prevent any more keypresses being sent on X11/Linux/Gnome?

https://askubuntu.com/questions/160522/python-gtk-event-ignore

您可能想要修改您的问题以显示您当前的处理方式 key-presses。例如,这是一个 command-line 程序,而您正在使用 curses?

如果 os.uname to return the os information or sys.platform 不可用,您可以使用。 sys.platform 的 Python 文档指出 OSX 苹果机器返回 'darwin'。

如果平台是 darwin,那么您可以在您的代码中忽略任何您想要的 key-presses。

编辑(因更改问题而更新): 如果你想在调用某个函数时忽略 key-presses,你可以使用 lock 来停止 key-press 函数调用和你的特定函数一起执行。

这是一个使用锁的例子,这可能不是运行,但它应该让你大致了解需要什么。

import _thread

a_lock = _thread.allocate_lock()

def certainFunction():
    with a_lock:
        print("Here's the code that you don't want to execute at the same time as onSpecificKeyCall()")

def onSpecificKeyCall():
    with a_lock:
        print("Here's the code that you don't want to execute at the same time as certainFunction()")

或者,视情况而定,当您不想被按键打断的函数被调用时,您可以再次调用 onkey(),忽略特定的键,调用一个函数什么都不做。当您的特定功能完成后,您可以再次调用 onkey() 以将按键绑定到处理输入的功能。