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

2022-01-15 00:00:00 python kivy buildozer

问题描述

我正在尝试使用 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:pathtoappimgimage.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%.

相关文章