如何使可编辑标签在kivy中工作

问题描述 投票:0回答:1

以下代码打开窗口,标签位于顶部,标签在您单击后转为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)
python label kivy
1个回答
0
投票

根据docs

当光标位置改变时,选择自动更新。您可以从TextInput.selection_text属性中获取当前选定的文本。

在您的情况下,当您单击标签并出现在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())
© www.soinside.com 2019 - 2024. All rights reserved.