我试图为日期创建一个简单的TextInput,它将输入限制为数字,并自动填充(mm/dd/yy)格式的正斜杠。通过重新定义insert_text(),我成功地创建了一个过滤器,但当用户返回空格时,我也希望自动删除斜杠。但我不知道如何检测用户何时在文本输入中后退,以便在必要时触发事件来删除斜杠。
这里有一个片段解释了我想做什么,但是TextInput没有“on-key-up”属性。有办法加一个吗?还是更好的办法?

# .kv file

<DateInput>
    on_key_up: self.check_for_backspace(keycode) # not a true attribute

# .py file

class DateInput(TextInput):

    # checks if last character is a slash and removes it after backspace keystroke.  Not sure this would work.
    def check_for_backspace(self, keycode):
        if keycode[1] == 'backspace' and self.text[-1:] == '/':
            self.text = self.text[:-1]

    #filter for date formatting which works well aside from backspacing
    pat = re.compile('[^0-9]')
    def insert_text(self, substring, from_undo=False):
        pat = self.pat
        if len(substring) > 1:
            substring = re.sub(pat, '', (self.text + substring))
            self.text = ''
            slen = len(substring)
            if slen == 2:
                s = substring[:2] + '/'
            elif slen == 3:
                s = substring[:2] + '/' + substring[2:]
            elif slen == 4:
                s = substring[:2] + '/' + substring[2:] + '/'
            else:
                s = substring[:2] + '/' + substring[2:4] + '/' + substring[4:8]
        elif len(self.text) > 9:
            s = ''
        elif len(self.text) == 1:
            s = re.sub(pat, '', substring)
            if s != '':
                s = s + '/'
        elif len(self.text) == 4:
            s = re.sub(pat, '', substring)
            if s != '':
                s = s + '/'
        else:
            s = re.sub(pat, '', substring)
        return super(DateInput, self).insert_text(s, from_undo=from_undo)

最佳答案

由于版本1.9.0TextInputFocusBehavior固有的,因此如果您想在按backspace时检测,则必须使用keyboard_on_key_down()方法或keyboard_on_key_up()方法:

from kivy.app import App
from kivy.uix.textinput import TextInput

class DateInput(TextInput):
    def keyboard_on_key_down(self, window, keycode, text, modifiers):
        if keycode[1] == "backspace":
            print("print backspace down", keycode)
        TextInput.keyboard_on_key_down(self, window, keycode, text, modifiers)

    def keyboard_on_key_up(self, window, keycode, text, modifiers):
        if keycode[1] == "backspace":
            print("print backspace up", keycode)
        TextInput.keyboard_on_key_down(self, window, keycode, text, modifiers)


class MyApp(App):
    def build(self):
        return DateInput()

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

关于python - Kivy Python:检测文本输入中的退格键,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51093710/

10-16 13:04