Python 使用prompt_toolkit对按键做出反应
我正在尝试使用Python 使用prompt_toolkit对按键做出反应,python,keyboard,prompt-toolkit,Python,Keyboard,Prompt Toolkit,我正在尝试使用prompt\u 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
prompt\u 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}')
我希望该计划能够:
- 按下
时打印“hello world”Ctrl+T
- 按下
时退出Ctrl+X
- 按下
时,将d
的值加倍i
那么,如何创建一个键绑定来改变我的变量呢?如果您是从局部函数引用全局变量,只需指出这是您想要的,否则您是在引用一个不存在的局部变量
@bindings.add('d')
def _(event):
global i # fixes your problem
i *= 2
请参见上面的一行更改 有没有办法将变量传递给事件?@user8493571您需要为我提供更多的信息来回答这个问题,也许关闭这个问题并打开一个新的问题,因为我需要更多的上下文,您在用它做什么,评论不是一个很好的地方,因为它可能会引发一场大的对话。如果这个答案对原来的问题是正确的,你应该接受它并结束这个问题。
@bindings.add('d')
def _(event):
global i # fixes your problem
i *= 2