使用PyInstaller打包Python Turtle程序时无法加载图片文件的问题
解决PyInstaller打包Turtle程序时找不到图片文件的问题
问题描述
运行打包后的单文件可执行程序时出现错误:
tkinter.TclError: couldn't open "boiled-egg.gif": no such file or directory [3792] Failed to execute script 'main' due to unhandled exception!
程序在终端运行正常,但用PyInstaller/auto-py-to-exe打包为单文件后无法找到同目录下的boiled-egg.gif;不使用外部图片时打包正常。环境:Mac系统,Python 3.12.3,PyInstaller 6.9.0。
涉及代码片段:
class Food(Turtle): def __init__(self): super().__init__() self.shape("boiled-egg.gif") self.penup() self.speed("fastest") self.goto(Random().randint(-280, 280), Random().randint(-280, 280)) self.refresh()
原因分析
PyInstaller打包成单文件时,会将所有资源文件解压到系统临时目录(而非可执行文件所在目录),程序运行时直接用文件名查找图片,会找不到正确路径。
解决步骤
1. 修改代码,动态获取资源路径
导入sys和os模块,添加工具函数让程序在打包前后都能定位到图片:
import sys import os from turtle import Turtle from random import Random def get_resource_path(filename): try: # 打包后,PyInstaller会设置_MEIPASS指向临时资源目录 base_path = sys._MEIPASS except AttributeError: # 未打包时,使用当前脚本所在目录 base_path = os.path.dirname(os.path.abspath(__file__)) return os.path.join(base_path, filename) class Food(Turtle): def __init__(self): super().__init__() # 用动态路径加载图片 self.shape(get_resource_path("boiled-egg.gif")) self.penup() self.speed("fastest") self.goto(Random().randint(-280, 280), Random().randint(-280, 280)) self.refresh()
2. 打包时指定资源文件
使用PyInstaller命令时,通过--add-data参数将图片加入打包资源:
pyinstaller --onefile --add-data "boiled-egg.gif:." main.py
如果用auto-py-to-exe,在「Additional Files」选项中添加boiled-egg.gif,设置「Destination」为.即可。
3. (可选)用spec文件打包
若需要自定义配置,先生成spec文件:
pyinstaller --onefile main.py
打开生成的main.spec,修改datas字段添加图片:
a = Analysis( ['main.py'], datas=[('boiled-egg.gif', '.')], # 新增这一行 # 保留原有其他配置 )
再用spec文件重新打包:
pyinstaller main.spec
验证
打包完成后,直接运行可执行文件(或确保图片与exe在同一目录),程序即可正确加载图片。
内容的提问来源于stack exchange,提问作者Aseem Aishwarya
相关产品推荐
相关产品推荐

