如何使用 onefile 模式 pyinstaller 在 Kivy 应用程序中包含图像?

How to include image in Kivy application with onefile mode pyinstaller?

在过去的 8 小时里,我一直在努力让我的图像显示在我使用 pyinstaller 构建的 .exe 中。我的程序是用 kivy 写的。其他一切正常,但图像不显示。我已阅读 [this][2] 问题。那对我不起作用。或者我只是听错了答案。如果有人可以向我解释如何逐步进行,我将不胜感激。另外,如果有其他答案,也请考虑告诉我。

我将包含我的 main.py 文件:

#!/usr/bin/env python3

import os
import sys
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.image import Image
from kivy.uix.button import Button
from kivy.uix.textinput import TextInput
from kivy.uix.slider import Slider

class SayHello(App):
    def build(self):
        self.window = GridLayout()
        self.window.cols = 1
        self.window.size_hint = (0.6,0.7)
        self.window.pos_hint = {"center_x": 0.5, "center_y": 0.5}

        self.window.add_widget(Image(source = "say.png"))

        self.greeting = Label(
                        text = "Hello",
                        font_size = 40,
                        color = "#00FFCE"
                        )
        self.window.add_widget(self.greeting)
    
        self.slid = Slider(min = 0, max = 300, orientation = "horizontal")
        self.window.add_widget(self.slid)
    
    
        
    
        
        self.user = TextInput(
                    multiline = False,
                    padding_y = (20,20),
                    size_hint = (1, 0.4)
                    )
        self.window.add_widget(self.user)

        self.button = Button(
                      text = "Click me to greet you!",
                      size_hint = (1,0.5),
                      bold = True,
                      background_color = "00FFCE",
                      )
        
        self.button.bind(on_press = self.callback)
        self.window.add_widget(self.button)

        return self.window


    def slided(self, event):
        self.slid
    
    
    
    def callback(self, event):
        self.greeting.text = "Hello " + self.user.text + "!"



def resource_path(relative_path):
    """ Get absolute path to resource, works for dev and for PyInstaller """
    base_path = getattr(
        sys,
        '_MEIPASS',
        os.path.dirname(os.path.abspath(__file__)))
    return os.path.join(base_path, relative_path)

path = resource_path("say.png")
        





    

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


  [1]: 
  [2]: 

提前致谢!

问题在于您尝试修复路径:

def resource_path(relative_path):
    """ Get absolute path to resource, works for dev and for PyInstaller """
    base_path = getattr(
        sys,
        '_MEIPASS',
        os.path.dirname(os.path.abspath(__file__)))
    return os.path.join(base_path, relative_path)

path = resource_path("say.png")

只需将该代码替换为:

import kivy.resources

if getattr(sys, 'frozen', False):
    # this is a Pyinstaller bundle
    kivy.resources.resource_add_path(sys._MEIPASS)