如何获取Kivy TextInput或Label中的字符宽度

3

我在Kivy中有一个长内容的TextInput。我想知道TextInput的字符宽度,也就是行的长度?

textinput = TextInput(text="Open source Python library for rapid development of applications that make use of innovative user interfaces, such as multi-touch apps")

enter image description here


使用 cursor_colcursor_row 怎么样:http://kivy.org/docs/api-kivy.uix.textinput.html#kivy.uix.textinput.TextInput.cursor_col? - Iron Fist
@KhalilAmmour-خليلعمور 我认为 cursor_col 给出的是光标位置而不是行的宽度。 - Assem
是的,我的意思是,在 cursor_colcursor_row 之间进行组合检查,以存储 cursor_col 的值和/或下一个新行时的值。当 cursor_row = +1 时,那就应该是该行的长度。你明白我的意思吗? - Iron Fist
我明白你的意思,这是一种hack方法。但不确定它是否有效。 - Assem
那么,也许你可以将其实现为函数并发布到Kivy模块中... :) - Iron Fist
2个回答

1
您可以使用_lines属性检查TextInput的行。要获取它们的长度,请使用len()内置函数:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout

from kivy.lang import Builder

Builder.load_string("""

<MyWidget>:
    Button:
        text: "Print width"
        on_press: print([len(line) for line in ti._lines])
    TextInput
        text: "Open source Python library for rapid development of applications that make use of innovative user interfaces, such as multi-touch apps"
        id: ti
""")

class MyWidget(BoxLayout):
    pass

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

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

谢谢。这给出了该行中字符的数量,而不是总宽度。 - Assem
1
由于字符没有固定的宽度,例如“.”字符比“X”字符更窄,因此您无法获得总值。使用该代码来比较仅由“.”和“X”字符组成的行的宽度。 - Nykakin

0
为了改进这个讨论: 在TextInput._lines_labels中,有一个字段大小(元组)[0],它表示行的宽度。每一行都是如此。只需迭代并寻找最大值,然后'voilà'。 这适用于任何字体(prop或非prop)。
Radek

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接