teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

3

--add-data -> --add-binary に変更

2020/06/30 14:14

投稿

teamikl
teamikl

スコア8817

answer CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  自動で認識されないので、これは追加で指定が必要ですね。
4
4
  ディレクトリ構成次第ですが、一例を挙げるとコマンドラインで指定する場合は
5
- --add-data"images/*.png;images" ← ; の左側がプロジェクト内で参照する画像のpath/ 右側が実行時展開されるフォルダ
5
+ --add-binary "images/*.png;images" ← ; の左側がプロジェクト内で参照する画像のpath/ 右側が実行時展開されるフォルダ
6
6
 
7
7
  一度実行した後に生成されるspec ファイル編集でも指定できます。
8
8
 

2

--onefile付きで実行時のファイルのPATHを解決する

2020/06/30 14:14

投稿

teamikl
teamikl

スコア8817

answer CHANGED
@@ -15,4 +15,37 @@
15
15
  exe化してから実行した場合で別ける必要があります。
16
16
 
17
17
  デバッグ時は、大抵スクリプトファイルのある場所がカレントディレクトリですが、
18
- インストール後は、exeファイルの場所がカレントディレクトリとは限らない点にも注意。
18
+ インストール後は、exeファイルの場所がカレントディレクトリとは限らない点にも注意。
19
+
20
+ 追記: コード側の対応方法 (resource_path 関数は[bundling-data-files-with-pyinstaller-onefile](https://stackoverflow.com/questions/7674790/bundling-data-files-with-pyinstaller-onefile) から借用
21
+
22
+ ```
23
+
24
+ import os
25
+ import sys
26
+ import tkinter as tk
27
+
28
+ def resource_path(relative_path):
29
+ try:
30
+ # PyInstaller creates a temp folder and stores path in _MEIPASS
31
+ base_path = sys._MEIPASS
32
+ except Exception:
33
+ base_path = os.path.abspath(".")
34
+
35
+ return os.path.join(base_path, relative_path)
36
+
37
+
38
+ IMG_PATH = resource_path("./images/sample.png")
39
+
40
+
41
+ def main():
42
+ root = tk.Tk()
43
+ photo = tk.PhotoImage(file=IMG_PATH)
44
+ button = tk.Button(root, image=photo)
45
+ button.pack()
46
+ root.mainloop()
47
+
48
+
49
+ if __name__ == '__main__':
50
+ main()
51
+ ```

1

余分なコードが残っていたので削除

2020/06/30 13:22

投稿

teamikl
teamikl

スコア8817

answer CHANGED
@@ -1,6 +1,6 @@
1
1
  > プログラムの中で利用している画像のためのフォルダ、パッケージは PyInstallerから認識できているのかなぁ という不安があります。
2
2
 
3
- 自動で認識されないので、これは追加で指定が必要ですね。--add-data, --add-binary
3
+ 自動で認識されないので、これは追加で指定が必要ですね。
4
4
  ディレクトリ構成次第ですが、一例を挙げるとコマンドラインで指定する場合は
5
5
  --add-data"images/*.png;images" ← ; の左側がプロジェクト内で参照する画像のpath/ 右側が実行時展開されるフォルダ
6
6