2017-02-15 129 views
2

我想用pyinstaller構建一個文件exe,但我不確定圖像的文件路徑應該在主python文件中。pyinstaller捆綁圖像的文件路徑?

在我使用的MEIPASS代碼我主要的Python文件的頂部:

def resource_path(relative_path): 
""" Get absolute path to resource, works for dev and for PyInstaller """ 
try: 
    # PyInstaller creates a temp folder and stores path in _MEIPASS 
    base_path = sys._MEIPASS 
except Exception: 
    base_path = os.path.abspath(".") 

return os.path.join(base_path, relative_path) 

From this page

這是當前的代碼,我爲每個圖像文件:

root.iconbitmap('C:\\Users\\username\\Downloads\\TripApp\\BennySM.ico') 
filename = PhotoImage(file = 'C:\\Users\\username\\Downloads\\TripApp\\BgSM.gif') 

我知道這些不是最好的文件路徑,但我不知道我需要添加什麼,所以python文件知道在哪裏看。圖像與exe文件捆綁在一起,如果我將exe文件添加到數據文件中,它會找到圖像並運行。

謝謝!我之前嘗試添加resource_path,但我在頂部的define部分中缺少文件路徑。

再次感謝!

回答

0

問題:如何在pyinstaller內置程序中使用數據文件?

讓我們首先假設Python腳本正在工作時,作爲一個腳本運行,而下面一行是在腳本:

filename = PhotoImage(file='C:\\Users\\username\\Downloads\\TripApp\\BgSM.gif') 

該行表示腳本檢索從文件固定的目錄(可能不是最佳實踐,但是對於示例而言很好),並將該文件轉換爲PhotoImage()對象實例。這將是我們的基準。

當我們的腳本作爲pyinstaller構建的程序運行時,需要做三件事才能成功使用此文件。

1.在pyinstaller構建,將文件移動到已知位置

該步驟完成通過添加datas指令到`的.spec」文件。有關如何做到這一點的更多信息,請參見this post。但總之,這將是需要的:

datas=[ 
    ('C:\\Users\\test\\Downloads\\TripApp\\BgSM.gif', 'data'), 
    ... 
], 

請注意,元組中有兩個元素。第一個元素是我們的.gif文件的路徑,因爲它在將它打包到pyinstaller可執行文件之前存在於工作python腳本中。元組的第二個元素是運行可執行文件時該文件所在的目錄。

2.在運行時,發現我們的.gif文件

這裏是從問題中所說的功能,重鑄使用方法:

  1. 從例子中的絕對路徑,當腳本作爲腳本運行,或者
  2. 腳本作爲pyinstaller構建程序運行時,在datas元組中指定的路徑。

代碼:

def resource_path(relative_path): 
    """ Get absolute path to resource, works for dev and for PyInstaller """ 
    try: 
     # PyInstaller creates a temp folder and stores path in _MEIPASS, 
     # and places our data files in a folder relative to that temp 
     # folder named as specified in the datas tuple in the spec file 
     base_path = os.path.join(sys._MEIPASS, 'data') 
    except Exception: 
     # sys._MEIPASS is not defined, so use the original path 
     base_path = 'C:\\Users\\test\\Downloads\\TripApp' 

    return os.path.join(base_path, relative_path) 

3重鑄基線到我們pyinstaller內置程序

工作,所以現在我們可以構建我們的路徑。 gif文件作爲腳本運行時,或作爲pyinstaller構建的程序,我們的基線變爲:

filename = PhotoImage(file=resource_path('BgSM.gif'))