Kivy 文本输入框查看末尾
这看起来是个很有用的功能,也许我错过了什么,但Kivy的文本输入框有没有类似于tkinter中Text.see(END)
的方法?我查看了do_cursor_movement
,但它只是移动光标,并不会改变显示的内容。
3 个回答
1
我对Kivy一点都不熟悉,也没有测试过我的回答,但如果我理解文档没错的话,只要把cursor
这个属性设置到行的末尾,就能实现你想要的效果。
引用内容:
光标
Tuple of (row, col) values indicating the current cursor position.
如果你想移动光标,可以设置一个新的(行,列)。滚动区域会自动更新,以确保光标在视口内可见。
2
我发现这个问题可以通过使用包含文本输入框的滚动视图来解决。在一个 .kv 文件中可以这样写:
ScrollView:
id: scroll1
size_hint_x: 0.6
TextInput:
readonly: True
id: main
size_hint: 1, None
height: max(self.minimum_height, scroll1.height)
然后,只需要调用 self.ids['scroll1'].scroll_y = 0
这行代码,就能把文本输入框滚动到最底部。
1
我发现了一个问题,就是光标在启动时没有正确设置。在我下面的例子中,虽然文本的顶部是显示出来的,但在添加了TextInput
的代码后,光标的位置却显示为(0, 100)
。这导致底部的按钮没有反应,直到你点击TextInput
(这会改变光标的位置)或者点击顶部的按钮。
如果你想看看我说的是什么,只需把Clock.schedule_once(lambda _: setattr(root.ids['ti'], 'cursor', (0, 0)))
这一行注释掉。
我在Ubuntu 14.04上测试了这个代码,使用的是Kivy 1.8.1-dev版本(git: 1149da6bf26ff5f27536222b4ba6a874456cde6e):
import kivy
kivy.require('1.8.1')
from kivy.app import App
from kivy.lang import Builder
from kivy.clock import Clock
root = Builder.load_string('''
BoxLayout:
orientation: 'vertical'
BoxLayout:
TextInput:
id: ti
Label:
size_hint_x: None
width: sp(80)
text: str(ti.cursor)
BoxLayout:
size_hint_y: None
height: sp(128)
Widget
Button:
text: 'Top'
on_press: ti.cursor = (0, 0)
Button:
text: 'Bottom'
on_press: ti.cursor = (0, len(ti._lines) - 1)
Widget
''')
class TestApp(App):
def build(self):
text = ''
for i in xrange(100):
text += 'Line %d\n' % (i + 1,)
root.ids['ti'].text = text
# fix the cursor pos
Clock.schedule_once(lambda _: setattr(root.ids['ti'], 'cursor', (0, 0)))
return root
if __name__ == '__main__':
TestApp().run()