Kivy文本输入如何从右侧开始打字

  • 本文关键字:开始 文本 Kivy python kivy
  • 更新时间 :
  • 英文 :


我正在用kivy构建一个简单的计算器,如何使光标自动从右到左开始打字

不幸的是,事情并没有那么简单。不确定这是否正是您要找的,但这是我为类似案例编写的TextInput的扩展。它使文本保持右调整。请注意,这期望文本是合法的浮点数。如果您不想要该限制,只需删除调用float的代码:

class FloatInputRight(TextInput):
def __init__(self, **kwargs):
super(FloatInputRight, self).__init__(**kwargs)
self.multiline = False
def right_adjust(self, text):
if text == '':
return text
max_width = self.width - self.padding[0] - self.padding[2]
new_text = text
text_width = self._get_text_width(new_text, self.tab_width, self._label_cached)
while text_width < max_width:
new_text = ' ' + new_text
text_width = self._get_text_width(new_text, self.tab_width, self._label_cached)
while text_width >= max_width:
if new_text[0] != ' ':
break
else:
new_text = new_text[1:]
text_width = self._get_text_width(new_text, self.tab_width, self._label_cached)
return new_text
def on_size(self, instance, value):
super(FloatInputRight, self).on_size(instance, value)
if len(self._lines) == 0:
return True
cc, cr = self.cursor
cur_text = self._lines[cr]
initial_len = len(cur_text)
super(FloatInputRight, self)._refresh_text(self.right_adjust(cur_text))
final_len = len(self._lines[cr])
self.cursor = self.get_cursor_from_index(final_len - (initial_len - cc))
return True
def delete_selection(self, from_undo=False):
if not self._selection:
return
cr = self.cursor[1]
initial_len = len(self._lines[cr])
a, b = self._selection_from, self._selection_to
if a > b:
a, b = b, a
super(FloatInputRight, self).delete_selection(from_undo=from_undo)
cur_text = self._lines[cr]
super(FloatInputRight, self)._refresh_text(self.right_adjust(cur_text))
final_len = len(self._lines[cr])
self.cursor = self.get_cursor_from_index(final_len - (initial_len - b))
def do_backspace(self, from_undo=False, mode='bkspc'):
cc, cr = self.cursor
initial_len = len(self._lines[cr])
super(FloatInputRight, self).do_backspace(from_undo=from_undo, mode=mode)
cc, cr = self.cursor
cur_text = self._lines[cr]
super(FloatInputRight, self)._refresh_text(self.right_adjust(cur_text))
final_len = len(self._lines[cr])
self.cursor = self.get_cursor_from_index(final_len - (initial_len-cc) + 1)
def insert_text(self, the_text, from_undo=False):
cc, cr = self.cursor
cur_text = self._lines[cr]
initial_len = len(cur_text)
new_text = self.right_adjust(cur_text[:cc] + the_text + cur_text[cc:])
try:
num = float(new_text) # throw exception if new_text is invalid float
except ValueError:
return
self._lines[cr] = ''
super(FloatInputRight, self).insert_text(new_text, from_undo=from_undo)
final_len = len(self._lines[cr])
self.cursor = self.get_cursor_from_index(final_len - (initial_len-cc))
def set_right_adj_text(self, text):
num = float(text)  # throws exception if text is invalid float
self._refresh_text(self.right_adjust(text))

最新更新