Kivy:TextInput选区文本异常——仅支持从左到右选中文本
Got it, let's tackle this selection direction issue. The problem here is that when you select text from right to left in Kivy's TextInput, the selection_from value ends up being larger than selection_to. Your current code assumes selection_from is always the leftmost index, which breaks the text manipulation when the selection direction is reversed.
To fix this, we just need to normalize the selection indices by taking the minimum and maximum of selection_from and selection_to—this gives us the correct start and end positions, no matter which direction the user dragged to select text.
Here's the updated code with the fix applied to the emphasize method:
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 # Normalize indices to handle both left-to-right and right-to-left selection start = min(begin, end) end_idx = max(begin, end) new_text = text[:start] + ' **' + selection + '** ' + text[end_idx:] 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()
What Changed:
- Added two lines to calculate
start(the leftmost selection index) andend_idx(the rightmost index) usingmin()andmax(). This ensures we always slice the original text correctly, regardless of selection direction. - Updated the
new_textconstruction to use these normalized indices instead of the rawbeginandendvalues.
Now your emphasize feature will work just like standard text editors—supporting both left-to-right and right-to-left text selection without breaking.
内容的提问来源于stack exchange,提问作者user8694101

