使用buildozer构建后,kivy应用程序中文件的路径无效

问题描述:

我正在尝试使用buildozer虚拟机构建一个kivy应用程序.只要我的main.py不包含文件的任何特定路径,它就可以正常工作. 例如,在我的应用程序中,我想显示图像.如果我在Windows上运行,则将源指定为

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

在Ubuntu中应该是

In Ubuntu it would be

/home/pathtoapp/img/image.png

如果我尝试使用buildozer来构建应用程序,则会收到错误消息:

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

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

,然后是上面的路径. 这是一个可以在Ubuntu上运行的示例,但是在部署到我的Android手机上时会给出上述错误消息:

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.

当然,它会给出错误消息.您在Android或Windows上都没有这样的路径.使用Kivy,您可以使用相对路径,如果您使用使用类似的东西:

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'

(如果该文件位于您的main.py/main.pyo目录中).过去,它有时在Android上对我不起作用,所以我有了一个安全陷阱",这样我就不会再遇到此问题了(它现在应该可以工作,但是比后悔更安全):

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

它将返回到main.py文件夹的路径,您可以像这样使用它:

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'

我也习惯于将路径放在App类中,以便我始终可以访问它.

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

有关更多花式路径的信息,请参见 App.user_data_dir ,它也为您解决了这个问题,但是如果卸载后留下一些混乱,这不是一个好方法,例如如果您使用的是Windows,并且决定删除应用程序,但是以某种方式忘记从%appdata%%localappdata%删除文件夹.

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%.