【发布时间】:2018-08-30 04:41:42
【问题描述】:
以下代码创建一个Kivy 应用程序,该应用程序只有一个屏幕MainScreen,显示Label 和TextInput 对象。
如果您在应用首次加载时提供了一些键盘输入,它会在控制台中打印有关按下哪个键的信息。但是,如果您随后单击 TextInput 对象,键盘将重新聚焦,以便您可以键入 TextInput 对象。但是,一旦您单击退出 TextInput 对象,例如在标签或背景上,按更多键,不执行相同的控制台打印操作;似乎键盘没有从TextInput 对象“散焦”。
点击TextInput 对象后如何重新获得键盘焦点?
from kivy.app import App
from kivy.lang import Builder
from kivy.core.window import Window
from kivy.uix.screenmanager import Screen, ScreenManager
from kivy.uix.textinput import TextInput
kv = '''ScreenManagement:
MainScreen:
<MainScreen>:
name: "main"
BoxLayout:
Label:
text: "Label"
font_size: 20
size_hint: 0.2,0.1
TextInput
input_filter: 'float'
font_size: 20
hint_text: "Input Text"
size_hint: 0.2,0.1'''
class MainScreen(Screen):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self._keyboard = Window.request_keyboard(self._keyboard_closed, self)
self._keyboard.bind(on_key_down=self._on_keyboard_down)
def _keyboard_closed(self):
self._keyboard.unbind(on_key_down=self._on_keyboard_down)
self._keyboard = None
def _on_keyboard_down(self, keyboard, keycode, text, modifiers):
print('INFO: The key', keycode, 'has been pressed')
return True # return True to accept the key. Otherwise, it will be used by the system.
class ScreenManagement(ScreenManager):
pass
class MainApp(App):
def build(self):
return Builder.load_string(kv)
if __name__ == "__main__":
MainApp().run()
【问题讨论】:
-
Kivy IRC 上的用户也提供了这个答案:pastebin.com/nYs4fHvT,它创建了一个按钮来重新聚焦键盘。
标签: python textbox focus kivy keyboard-events