如何在 python-prompt-toolkit 中将 pageup/pagedown 键绑定添加到 TextArea?
How do you add pageup/pagedown keybindings to TextArea in python-prompt-toolkit?
我们以calculator.py为例。
要添加与鼠标滚轮一起使用的滚动条,您需要更改:
output_field = TextArea(style="class:output-field", text=help_text)
至:
output_field = TextArea(style="class:output-field", text=help_text, scrollbar=True)
但是您会添加或更改什么来使用向上翻页和向下翻页键滚动 TextArea?
# The key bindings.
kb = KeyBindings()
@kb.add("pageup")
def _(event):
# What goes here?
pass
@kb.add("pagedown")
def _(event):
# What goes here?
pass
改变焦点
最简单的方法可能是导入 focus_next
(或 focus_previous
)
from prompt_toolkit.key_binding.bindings.focus import focus_next
并将其绑定到 Control-Space(或其他任何东西)。
# The key bindings.
kb = KeyBindings()
kb.add("c-space")(focus_next)
保持专注
您还可以,为了看似将注意力集中在 input_field
上,导入 scroll_page_up
和 scroll_page_down
from prompt_toolkit.key_binding.bindings.page_navigation import scroll_page_up, scroll_page_down
然后将焦点切换到 output_field
,调用 scroll_page_up
/scroll_page_down
,最后将焦点切换回 input_field
。
# The key bindings.
kb = KeyBindings()
@kb.add("pageup")
def _(event):
w = event.app.layout.current_window
event.app.layout.focus(output_field.window)
scroll_page_up(event)
event.app.layout.focus(w)
@kb.add("pagedown")
def _(event):
w = event.app.layout.current_window
event.app.layout.focus(output_field.window)
scroll_page_down(event)
event.app.layout.focus(w)
我们以calculator.py为例。
要添加与鼠标滚轮一起使用的滚动条,您需要更改:
output_field = TextArea(style="class:output-field", text=help_text)
至:
output_field = TextArea(style="class:output-field", text=help_text, scrollbar=True)
但是您会添加或更改什么来使用向上翻页和向下翻页键滚动 TextArea?
# The key bindings.
kb = KeyBindings()
@kb.add("pageup")
def _(event):
# What goes here?
pass
@kb.add("pagedown")
def _(event):
# What goes here?
pass
改变焦点
最简单的方法可能是导入 focus_next
(或 focus_previous
)
from prompt_toolkit.key_binding.bindings.focus import focus_next
并将其绑定到 Control-Space(或其他任何东西)。
# The key bindings.
kb = KeyBindings()
kb.add("c-space")(focus_next)
保持专注
您还可以,为了看似将注意力集中在 input_field
上,导入 scroll_page_up
和 scroll_page_down
from prompt_toolkit.key_binding.bindings.page_navigation import scroll_page_up, scroll_page_down
然后将焦点切换到 output_field
,调用 scroll_page_up
/scroll_page_down
,最后将焦点切换回 input_field
。
# The key bindings.
kb = KeyBindings()
@kb.add("pageup")
def _(event):
w = event.app.layout.current_window
event.app.layout.focus(output_field.window)
scroll_page_up(event)
event.app.layout.focus(w)
@kb.add("pagedown")
def _(event):
w = event.app.layout.current_window
event.app.layout.focus(output_field.window)
scroll_page_down(event)
event.app.layout.focus(w)