大家好,有人可以帮我吗,我想在 kivy textinput 或 label 中读取文本文件

Hello everyone, can someone help me, I want to read a text file in kivy textinput or label

进口:

from kivy.app import App
from kivy.lang import Builder
from kivy.properties import StringProperty
from kivy.uix.textinput import TextInput
kv = '''
BoxLayout:
    orientation: 'vertical'
    text: newList
    TextInput:
        id: newList
    Button:
        text: 'click'
        on_press: app.clicked()

'''

MyApp class:

class MyApp(App):
    text = StringProperty('read.text')

    def build(self):
        return Builder.load_string(kv)

    def clicked(self):
        file = open('read.text', 'r')
        f = file.readlines()
        newList = []
        for line in f:
            newList.append(line.strip())
        print(newList)
        self.root.ids.your_textinput.text = (newList)


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

当我按 运行 时出现此消息(AttributeError:'list' 对象没有属性)。

首先您要打开名为 read.text 的文件,该文件不存在。文本文件的扩展名为 .txt。由于此类文件不存在,因此不会打开文件,因此不会向列表中添加任何内容 newList。所以你所要做的就是将 .text 更改为 .txt 第二件事是你给了你的文本输入字段与列表相同的 id,这可能会在以后导致错误。此外,在执行 self.root.ids.your_textinput.text = (newList) 时,您提供的是列表而不是文本,这也会导致错误。所以你的最终代码是:

from kivy.app import App
from kivy.lang import Builder
from kivy.properties import StringProperty
from kivy.uix.textinput import TextInput

kv = '''
BoxLayout:
    orientation: 'vertical'
    TextInput:
        id: text_field
    Button:
        text: 'click'
        on_press: app.clicked()

'''

class MyApp(App):
    text = StringProperty('read.txt')

    def build(self):
        return Builder.load_string(kv)

    def clicked(self):
        file = open('read.txt', 'r')
        f = file.readlines()
        self.root.ids.text_field.text = (''.join(f))


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