【问题标题】:How to use input to TextInput in kivy to get different output如何在kivy中使用TextInput的输入来获得不同的输出
【发布时间】:2020-05-18 17:09:19
【问题描述】:

我写了以下代码。

#-*- coding: utf-8 -*-
from kivy.config import Config
from kivy.uix.button import Button
from functools import partial
Config.set('graphics', 'width', 300)
Config.set('graphics', 'height', 300)

from kivy.lang import Builder
Builder.load_string("""
<KeybindTestWidget>:
    BoxLayout:
        size: root.size
        orientation: 'vertical'

        TextInput:
            id: textinput1
            size_hint_y: 0.45
            text: ""
            on_focus: root.set_activeTextInput("textinput1")

        BoxLayout:
            size_hint_y: 0.1

        TextInput:
            id: textinput2
            size_hint_y: 0.45
            text: ""
            on_focus: root.set_activeTextInput("textinput2")
""")

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.textinput import TextInput
from kivy.uix.boxlayout import BoxLayout
from kivy.core.window import Window

class KeybindTestWidget(Widget):
    def __init__(self, **kwargs):
        super(KeybindTestWidget, self).__init__(**kwargs)

        self.bufHotKeyTextinputName = ""

        #key bind
        self._keyboard = Window.request_keyboard(
            self._keyboard_closed, self, 'text')
        if self._keyboard.widget:
            pass
        self._keyboard.bind(on_key_down=self._on_keyboard_down)
        self._keyboard.bind(on_key_up=self._on_keyboard_up)

    def _keyboard_closed(self):
        pass

    def _on_keyboard_down(self, keyboard, keycode, text, modifiers):
        self.ids[self.bufHotKeyTextinputName].text = keycode[1]
        return True

    def _on_keyboard_up(self, keyboard, keycode):
        return True

    def set_activeTextInput(self, textInputName, *args):
        self.bufHotKeyTextinputName = textInputName

class TestApp(App):
    def __init__(self, **kwargs):
        super(TestApp, self).__init__(**kwargs)

    def build(self):
        return KeybindTestWidget()

if __name__ == '__main__':
    TestApp().run()

在上面的代码中,如果我在 TextInput 处于焦点时从键盘键入,文本将响应键输入而改变。

例如,如果我按键盘上的空格键,TextInput 将显示“空格键”。

但是,上面的代码有一个问题。

当我按下键盘上的“a”时会发生这种情况,如下图所示,TextInput 显示“aa”。

_on_keyboard_down 函数在键盘输入之前执行,所以它复制了输入。

我已尝试只读 TextInput 选项,这会使 on_key_down 无响应。

有什么好的解决办法吗?

【问题讨论】:

    标签: python kivy


    【解决方案1】:

    一种方法是使用Clock 安排调用TextInput 完成其字母的绘制(我们将删除)。
    您还需要from functools import partial

        def _on_keyboard_down(self, keyboard, keycode, text, modifiers):
            Clock.schedule_once(partial(self.clear_and_set, keycode))
            return True
    
        def clear_and_set(self, keycode, *args):
            self.ids[self.bufHotKeyTextinputName].text = keycode[1]
    

    【讨论】:

      猜你喜欢
      • 2014-10-23
      • 1970-01-01
      • 1970-01-01
      • 2020-11-24
      • 2019-03-13
      • 2017-08-24
      • 2012-02-19
      • 2017-09-25
      • 1970-01-01
      相关资源
      最近更新 更多