我正在尝试为日期创建一个简单的 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.0 TextInput
是 FocusBehavior
所固有的所以如果你想检测你何时按下退格键,你必须使用 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 - 基维 python : Detect backspace in Text Input,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51093710/