简体   繁体   中英

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

imports:

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()

This message appears when I press run (AttributeError: 'list' object has no attribute).

First of all you are opening file named read.text which doesn't exist. Text files have extension .txt . As such file doesn't exist the file isn't opened and so nothing is added to the list newList . So all you have to do is change .text to .txt Second thing is that you have given your textinput field the same id as the list which may cause error later. Also while doing self.root.ids.your_textinput.text = (newList) you are providing a list instead of providing text, which will also cause error. So your final code would be:

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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