繁体   English   中英

大家好,谁能帮帮我,我想在 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 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' object 没有属性)。

首先,您正在打开名为read.text的文件,该文件不存在。 文本文件的扩展名为.txt 由于此类文件不存在,因此文件未打开,因此不会将任何内容添加到列表newList中。 因此,您所要做的就是将.text更改为.txt第二件事是您为 textinput 字段提供了与列表相同的 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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM