Kivy:TextInput selection_text 问题

Kivy: TextInput selection_text issue

这是从 复制的简单第一个编辑器的代码,在这段代码中 selection_text 被所需的标签包围,但这是一个问题,我只能 select 文本来自从左到右,当文本从右到左 selected 时,它不像以前那样工作,是否有可能像其他文本编辑器一样从任何一侧 select?

from kivy.app import App
from kivy.base import Builder
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout



Builder.load_string("""
<root_wgt>:
    orientation: 'vertical'
    BoxLayout:
        size_hint_y:0.2
        Button:
            text: 'Emphasize'
            on_press: root.emphasize()
        Button:
            text: 'Section Header'
            on_press: root.add_section_header()
        Button:
            text: 'Subection Header'
            on_press: root.add_sub_section_header()

    BoxLayout:
        orientation: 'vertical'
        TextInput:
            id: textinput

        RstDocument:
            id: rstdocument
            text: textinput.text
""")


class root_wgt(BoxLayout):
    def emphasize(self):
        text = self.ids.textinput.text
        selection = self.ids.textinput.selection_text
        begin = self.ids.textinput.selection_from
        end = self.ids.textinput.selection_to
        new_text = text[:begin] + ' **' + selection + '** ' + text[end:]
        self.ids.textinput.text = new_text
        self.ids.rstdocument.render()

    def add_section_header(self):
        self.ids.textinput.insert_text("""\n==============""")

    def add_sub_section_header(self):
        self.ids.textinput.insert_text("""\n-----------------""")

class MyApp(App):
    def build(self):
        return root_wgt()

if __name__ == '__main__':
    MyApp().run()

问题是因为当你select从右到左selection_to大于selection_from所以提取数据导致重复元素导致这种不当行为,解决办法beginend 是否正确排序,我们使用 sorted:

def emphasize(self):
    text = self.ids.textinput.text
    selection = self.ids.textinput.selection_text
    begin, end = sorted([self.ids.textinput.selection_from, self.ids.textinput.selection_to])
    new_text = text[:begin] + ' **' + selection + '** ' + text[end:]
    self.ids.textinput.text = new_text
    self.ids.rstdocument.render()