以下代码打开窗口,标签位于顶部,标签在您单击后转为textinput。
但是,一旦你开始输入并插入第一个键(任何键),文本就会缩短,你会突然丢失部分文本。例如:您点击标签> textinput出现>你输入'1'>文字变为'按此处然后尝试1'。
如何更改以下代码以停止文字消失?
import kivy
kivy.require('1.10.1')
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.textinput import TextInput
from kivy.uix.label import Label
from kivy.base import runTouchApp
from kivy.properties import BooleanProperty, ObjectProperty
#https://github.com/kivy/kivy/wiki/Editable-Label
class EditableLabel(Label):
edit = BooleanProperty(False)
textinput = ObjectProperty(None, allownone=True)
def on_touch_down(self, touch):
if self.collide_point(*touch.pos) and not self.edit:
self.edit = True
return super(EditableLabel, self).on_touch_down(touch)
def on_edit(self, instance, value):
if not value:
if self.textinput:
self.remove_widget(self.textinput)
return
self.textinput = t = TextInput(
text=self.text, size_hint=(None, None),
font_size=self.font_size, font_name=self.font_name,
pos=self.pos, size=self.size, multiline=False)
self.bind(pos=t.setter('pos'), size=t.setter('size'))
self.add_widget(self.textinput)
t.bind(on_text_validate=self.on_text_validate, focus=self.on_text_focus)
def on_text_validate(self, instance):
self.text = instance.text
self.edit = False
def on_text_focus(self, instance, focus):
if focus is False:
self.text = instance.text
self.edit = False
if __name__ == '__main__':
root = FloatLayout()
lbl = 'Press here and then try to edit (type a character), but text gets shortened suddenly.'
label = EditableLabel(text=lbl, size_hint_y=None, height=50, pos_hint={'top': 1})
root.add_widget(label)
runTouchApp(root)
答案 0 :(得分:0)
根据docs:
光标位置改变时,选择会自动更新。您可以从TextInput.selection_text属性中获取当前选定的文本。
在您的情况下,当您单击Label并出现在TextInput中时,光标会更改位置,以便选择文本。当选择了一个文本并且你写了一些它被替换时,这就是文本消失的原因。
解决方案是清理选择:
from kivy.clock import Clock
class EditableLabel(Label):
[...]
def on_edit(self, instance, value):
if not value:
if self.textinput:
self.remove_widget(self.textinput)
return
self.textinput = t = TextInput(
text=self.text, size_hint=(None, None),
font_size=self.font_size, font_name=self.font_name,
pos=self.pos, size=self.size, multiline=False)
self.bind(pos=t.setter('pos'), size=t.setter('size'))
self.add_widget(self.textinput)
t.bind(on_text_validate=self.on_text_validate, focus=self.on_text_focus)
Clock.schedule_once(lambda dt: self.textinput.cancel_selection())