我试图给我正在用KivyMD开发的应用程序上的MDTextField提供一个日期格式。此类字段的格式应为“dd/mm/yyyy”
我想做的是,一旦写入前两个数字,就会自动写入一个“/”,光标会跳到“/”右边的最后一个位置(例如“21/”)。以同样的方式,在第一个“/”后面写入其他2个数字后,将写入第二个“/”,光标将再次移动到末尾(例如“21/09/”
我已设法使两个“/”都出现,但我无法将光标放在所需位置。我的代码如下:
def apply_date_format(self):
# delete '/' if len is equal or less than 2 and final character is /
if len(self.ids.viajeInicio.text) =< 2 and (self.ids.viajeInicio.text).endswith('/'):
self.ids.viajeInicio.text = (self.ids.viajeInicio.text[:-1])
# first '/'
elif len(self.ids.viajeInicio.text) == 2 and (self.ids.viajeInicio.text).isnumeric():
self.ids.viajeInicio.text= self.ids.viajeInicio.text + "/"
# second '/'
elif len(self.ids.viajeInicio.text) == 5 and (self.ids.viajeInicio.text[3:5]).isnumeric():
self.ids.viajeInicio.text= self.ids.viajeInicio.text + "/"
# delete last '/' if len is <= 5 and last character is '/'
elif len(self.ids.viajeInicio.text) > 3 and len(self.ids.viajeInicio.text) <= 5 \
and (self.ids.viajeInicio.text).endswith('/'):
self.ids.viajeInicio.text = (self.ids.viajeInicio.text[:-1])
MDTextField的id为viajeInicio,并且在on_text事件上调用函数apply_date_format。代码如下:
MDTextField:
id: viajeInicio
hint_text: 'Ingresar Fecha de Inicio del Viaje'
pos_hint: {"x":0, "top":1}
helper_text: 'Formato de fecha: dd/mm/aaaa'
helper_text_mode: 'on_focus'
required: True
on_text:
root.apply_date_format()
写入“/”后,如何将光标位置移动到字符串的末尾。此外,有没有更好的方法来完成预期的任务
提前多谢
我认为扩展
MDTextField
类并超越它的insert_text()
方法更简单。大概是这样的:上面的代码使用了您的逻辑(添加了一些小的内容),由于它最终只调用了
MDTextField
的insert_text()
,所以所有光标移动都是为您处理的因此,您可以直接替换:
与:
在你的“kv”里。您不需要显式调用
insert_text()
方法,因为它是由基类TextInput
自动调用的。而且您也不需要on_text
条目您不再需要
apply_date_format()
方法相关问题 更多 >
编程相关推荐