Pyinstaller打包多Python文件及资源生成exe失败求助
Hey there! Let's work through fixing your PyInstaller packaging issue step by step—this is a super common problem when bundling Tkinter apps with external resources, so I’ve got you covered.
First, Fix the Resource Path Handling in Your Code
The biggest issue here is that when you package your app, the paths to your .ico and .xlsx files change. PyInstaller creates a temporary runtime folder, so you need to adjust your code to find these files both when developing and when running the bundled exe.
Add this helper function to your main.py (or any shared module):
import sys import os def get_resource_path(relative_path): try: # When running as bundled exe, use PyInstaller's temp path base_path = sys._MEIPASS except Exception: # When running in development, use current working directory base_path = os.path.abspath(".") return os.path.join(base_path, relative_path)
Then update wherever you load your icon and Excel file:
- For the Tkinter icon:
root.iconbitmap(get_resource_path("logo.ico")) - For the Excel file:
from openpyxl import load_workbook wb = load_workbook(get_resource_path("WAE_SW_NameCnvtn.xlsx"))
Use the Correct --add-data Syntax
Your earlier --add-data attempt failed because the syntax varies by OS, and you missed the target path. For Windows, use a semicolon (;) to separate the source file and the target directory (. means "same folder as the exe").
Here’s the full, correct PyInstaller command for Windows:
pyinstaller --windowed --name=NameCnvtn --add-data "logo.ico;." --add-data "WAE_SW_NameCnvtn.xlsx;." main.py
You don’t need to list the other .py files (like read_description.py) explicitly—PyInstaller automatically tracks imports from main.py, so it’ll include them as long as you’re using regular import statements.
Debug the "Failed to Execute Script" Error
If you still see that error, first build a console version of the exe (remove the --windowed flag) to see the actual error message:
pyinstaller --name=NameCnvtn --add-data "logo.ico;." --add-data "WAE_SW_NameCnvtn.xlsx;." main.py
Run the exe from a command prompt, and it’ll print exactly what’s broken (e.g., "file not found" for the Excel sheet, or a missing module). This is the fastest way to pinpoint issues.
Quick Environment Check
Since you’re on Python 3.6.4, make sure you’re using a compatible PyInstaller version. PyInstaller 4.x supports Python 3.6, so run this to upgrade if needed:
pip install --upgrade pyinstaller==4.10
Newer versions might have fixes for edge cases with Tkinter and openpyxl.
内容的提问来源于stack exchange,提问作者J Berjano

