Can someone provide a working code of loading data of text file to Label of kivy

Viewed 28

I am able to get the data in main app class and run it to get as Label but when I want to do the same by getting data in main app class where as defining Label in another class, it's giving name error.

import kivy  
from kivy.app import App # import Kivy App module to create 
from kivy.uix.label import Label # import Label Module
  
kivy.require('1.11.1')  
  
class MyKivyApp(App): 
      
   def build(self): 
      f=open('tesit.txt','r')
      t=f.read()
      
      return Label(text =t)
   
   rt=MyKivyApp()
   rt.run()
2 Answers

Your lines:

   rt=MyKivyApp()
   rt.run()

are inside the MyKivyApp. Just unindent those two lines to get them outside of the App class.

This's how we can read a text file and display it as label in another screen in kivy.

from kivy.app import App
from kivy.uix.screenmanager import Screen
from kivy.lang import Builder
from kivy.properties import StringProperty

class Screen1(Screen):
    f=open('test.txt','r')
    t=f.readlines()
    b=t[0]
    f.close()

class Screen2(Screen):
    username = StringProperty("")


root = Builder.load_string('''

<Screen1>:
    name:'xy'
    id:loginscreen
    BoxLayout:
        orientation: "vertical"
        Button:
            text:'Execution button'
            on_release: root.manager.current = "screen2"


<Screen2>:
    name: "screen2"
    FloatLayout:
        Label:
            text: root.username
        Button:
            text:'Back to menu'
            size_hint:.3,.3
            on_release: root.manager.current = "xy"

ScreenManager:
    Screen1:
        id:loginscreen
    Screen2:
        username: loginscreen.b

''')



class MyApp(App):
    def build(self):
        return root
r=MyApp()
r.run()
Related