TextInput:更改font_size时,光标意外移动

时间:2019-04-01 12:30:02

标签: python kivy

在Kivy文本输入中,每次更改font_size时,光标都会移动到文本结尾:

from kivy.app import App
from kivy.lang import Builder

KV = """
TextInput
    on_touch_down: self.font_size+=1
"""
class MyApp(App):
    def build(self):
        self.root = Builder.load_string(KV)

MyApp().run()

有没有办法解决或解决TextInput的这种行为?

1 个答案:

答案 0 :(得分:0)

  • prev_cursor中声明一个类属性class MyApp
  • 实施方法reset_cursor()prev_cursor恢复到TextInput的光标
  • on_touch_down事件,保存当前光标位置
  • on_touch_up事件,使用Kivy Clock.schedule_once()调用方法reset_cursor()

示例

main.py

from kivy.app import App
from kivy.lang import Builder

KV = """
#:import Clock kivy.clock.Clock

TextInput:
    on_touch_down:
        app.prev_cursor = self.cursor
        self.font_size += 1
    on_touch_up:
        Clock.schedule_once(lambda dt: app.reset_cursor(), 0.1)

"""


class MyApp(App):
    prev_cursor = ()

    def build(self):
        self.root = Builder.load_string(KV)

    def reset_cursor(self):
        self.root.cursor = self.prev_cursor


MyApp().run()