Path to files in kivy app not valid after building with buildozer

房东的猫 提交于 2021-02-19 08:11:15

问题


I'm trying to build a kivy app using the buildozer virtual machine. It works fine as long as my main.py doesn't contain any specific paths to files. For example, in my app I want to display an image. If I run on Windows, I would specifiy the source as

C:\pathtoapp\img\image.png

In Ubuntu it would be

/home/pathtoapp/img/image.png

If I try to build the app with buildozer I get the error message:

I/Python (15649): [Error   ] [Image  ] Error reading file 

and then the above path. Here is an example which works on Ubuntu but which gives the above error message when deployed to my Android phone:

from kivy.lang import Builder
from kivy.app import App
from kivy.uix.image import Image


kv = '''
BoxLayout:
    Image:
        source: app.image
'''


class Test(App):
    def build(self):
        self.image = '/home/kivy/Desktop/test/img/g3347.png' 
        print(self.image)
        return Builder.load_string(kv)

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

Now I'm puzzled as I don't know how to correctly specify the path in my code.


回答1:


Of course it gives an error message. You don't have such a path on Android, nor on Windows. With Kivy you can use relative paths, which should work if you use something like:

self.image = 'g3347.png'

if that file is in directory with your main.py/main.pyo. In past it sometimes didn't work for me on Android, so I have a "safety catch" so that I wouldn't encounter this problem anymore (it should work now, but better safe than sorry):

os.path.dirname(os.path.abspath(__file__))

which will return the path to the main.py folder and you can use it like this:

path = os.path.dirname(os.path.abspath(__file__))
self.image = path + '/g3347.png'

I'm also used to put the path in App class so that I could always access it.

For more fancy paths look at App.user_data_dir, which solves this problem for you too, though it isn't a nice one if you leave some mess after you if you uninstall e.g. if you are on Windows and you decide to remove your application, but somehow forget to remove your folder from %appdata% or %localappdata%.



来源:https://stackoverflow.com/questions/37773586/path-to-files-in-kivy-app-not-valid-after-building-with-buildozer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!