简体   繁体   中英

Linking main.py with .kv file

I am trying to get a label which has text of string stored in w variable in my main.py file and label is in .kv file let me show you both files.

Here's main.py file

from kivy.app import App
from kivy.properties import StringProperty

class ExampleApp(App):  
    def hell(self):
        w="hello world"
    def build(self):
        self.load_kv("exapmleapp.kv")

if __name__ == "__main__":
    ExampleApp().run()

And here is my .kv file.

Label:
    text:app.w

Every time when I run my main.py file, it gives me this error.

1: 2:Label: 3: text:app.w ... AttributeError: 'ExampleApp' object has no attribute 'w' File "/usr/local/lib/python2.7/dist-packages/kivy/lang.py", line 1649, in create_handler return eval(value, idmap) File "./exampleapp.kv", line 3, in text:app.w File "/usr/local/lib/python2.7/dist-packages/kivy/lang.py", line 858, in getattribute return getattr(object. getattribute (self, '_obj'), name) File "/usr/local/lib/python2.7/dist-packages/kivy/lang.py", line 2011, in _apply_rule value, rule, rctx['ids']) File "/usr/local/lib/python2.7/dist-packages/kivy/lang.py", line 1654, in create_handler cause=tb)

How can I get the label that has text stored in w variable in my main.py file

I don't think the .kv file can see attributes inside the function you are calling. As you can see in the example below, I've moved the 'w' attribute outside the function.

Edit: aah it seems you want to change the displayed label when function hell() is called. Firstly we need an easy way to refer to the label. Kivy uses the id tag , and the list of ids can be found in self.ids

Having the 'w' variable is no longer necessary, but I've left in there as it does answer the original question.

So, this should work in theory:

from kivy.app import App
from kivy.properties import StringProperty

class ExampleApp(App):  
  w = "hello"
  def hell(self):
    self.ids.mylabel.text = "world"
  def build(self):
    self.load_kv("exapmleapp.kv")

if __name__ == "__main__":
  ExampleApp().run()

And the .kv file:

Label:
  id: mylabel
  text:app.w

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