首页 > 解决方案 > 使用 prompt_toolkit 对按键做出反应

问题描述

我正在尝试使用prompt_toolkit,这样我就可以从用户那里获得输入,而无需等待他们按 Enter。我设法创建事件并将它们与键相关联,但我无法弄清楚如何从事件中实际操作我的程序。

from prompt_toolkit import prompt
from prompt_toolkit.application import run_in_terminal
from prompt_toolkit.key_binding import KeyBindings

i = 2

bindings = KeyBindings()

@bindings.add('c-t')
def _(event):
    " Say 'hello' when `c-t` is pressed. "
    def print_hello():
        print('hello world')
    run_in_terminal(print_hello)

@bindings.add('c-x')
def _(event):
    " Exit when `c-x` is pressed. "
    event.app.exit()

@bindings.add('d')
def _(event):
    i *= 2

text = prompt('> ', key_bindings=bindings)
print(f'You said: {text}')
print(f'i is now {i}')

我希望这个程序:

它执行 1 和 2,但 3 给出Exception local variable 'i' referenced before assignment. 但即使在 Python 文档中,我们也可以看到示例(https://docs.python.org/3/reference/executionmodel.html):

i = 10
def f():
    print(i)
i = 42
f()

那么如何创建一个改变我的变量的键绑定呢?

标签: pythonkeyboardprompt-toolkit

解决方案


您正在从局部函数引用全局变量,您只需要指出这是您想要的,否则您正在引用一个不存在的局部变量。

@bindings.add('d')
def _(event):
    global i     # fixes your problem
    i *= 2

见上面的一行更改!


推荐阅读