使用py2app打包Python脚本为Mac可执行文件时遇Tkinter错误求助
Let's break down your issues step by step and fix them one by one:
1. Fix the Python Version Confusion
You have two Python versions on your system: Anaconda's 3.6.2 (invoked with python) and another 3.6.4 (invoked with python3). This is critical because py2app will use the Python interpreter you run it with to collect dependencies.
- First, confirm you're using the Anaconda Python for packaging:
It should outputwhich python/Users/myname/anaconda3/bin/python. If not, activate your Anaconda environment first (or use the full path to run commands). - Never mix
pythonandpython3for this workflow — stick strictly to the Anaconda interpreter to avoid dependency mismatches.
2. Resolve the Tkinter & Unicode Error
The ValueError: character U+6573552f is not in range [...] error is a side effect of incorrect Tkinter configuration in your packaged app, often caused by Anaconda's Python not having its Tk resources properly bundled by py2app.
Step 2.1 Verify Anaconda's Tk Support
First, check if your Anaconda Python has working Tkinter:
# Run this in your Anaconda Python shell import tkinter tkinter._test()
If a test window pops up, Tk is working. If not, reinstall the Tk package in Anaconda:
conda install tk
Step 2.2 Update Your setup.py for Tkinter
Modify your setup.py to explicitly include Tkinter modules and ensure py2app bundles all required Tk resources:
from setuptools import setup APP = ['script1.py'] OPTIONS = { 'argv_emulation': True, 'plist': { 'PyRuntimeLocations': [ '@executable_path/../Frameworks/libpython3.6m.dylib', '/Users/myname/anaconda3/lib/libpython3.6m.dylib' ] }, # Explicitly include Tkinter modules 'includes': ['tkinter', 'tkinter.filedialog', 'tkinter.ttk'], # Force bundle the Anaconda Python framework 'frameworks': ['/Users/myname/anaconda3/lib/libpython3.6m.dylib'], # Bundle Tcl/Tk resource directories 'resources': ['/Users/myname/anaconda3/lib/tcl8.6', '/Users/myname/anaconda3/lib/tk8.6'] } setup( app=APP, options={'py2app': OPTIONS}, setup_requires=['py2app'], )
3. Clean & Re-Package Properly
Old build artifacts often cause unexpected issues. Clean them before re-packaging:
# Delete existing build/dist directories rm -rf build dist # Run py2app with Anaconda's Python python setup.py py2app
4. Fix Potential Encoding Issues
The Unicode error can also stem from system encoding mismatches. Before packaging, set these environment variables:
export LC_ALL=en_US.UTF-8 export LANG=en_US.UTF-8
Additional Troubleshooting Tips
- If you still get runtime errors, try installing py2app from Conda Forge instead of pip (it's more compatible with Anaconda):
pip uninstall py2app conda install -c conda-forge py2app - Double-check that the
libpython3.6m.dylibpath in yourplistexists. Run this to confirm:ls /Users/myname/anaconda3/lib/libpython3.6m.dylib
内容的提问来源于stack exchange,提问作者Bertil Johannes Ipsen

