Ubuntu 16.04下Python 2.7.14引入Tkinter失败求助
Hey there, let’s work through this Tkinter import issue step by step. You mentioned you’ve already installed tk and tcl but still can’t get Tkinter to load—here are actionable solutions to resolve this:
1. First, locate where Tkinter.py is stored
We need to find the exact path of the Tkinter module file on your system. Run this command in your terminal:
find /usr -name "Tkinter.py" 2>/dev/null
This searches your system for the file and suppresses permission-related errors. On Ubuntu 16.04, the typical output will be something like /usr/lib/python2.7/lib-tk/Tkinter.py.
2. Add the directory to Python’s module search path
Once you have the directory path (e.g., /usr/lib/python2.7/lib-tk/), you can add it in a few ways:
Option 1: Temporary fix (per script)
Add these lines at the very top of your Python script before importing Tkinter:
import sys sys.path.append("/usr/lib/python2.7/lib-tk/") # Replace with your actual path import Tkinter
This only applies to that specific script run—perfect for quick testing.
Option 2: Permanent fix (user-wide)
Edit your bash profile to set the PYTHONPATH environment variable permanently:
- Open your
.bashrcfile in a text editor:nano ~/.bashrc - Add this line at the end (replace the path with your found directory):
export PYTHONPATH="/usr/lib/python2.7/lib-tk/:$PYTHONPATH" - Save and exit, then apply the changes immediately:
source ~/.bashrc
Now every time you open a terminal, Python will automatically include this directory in its module search path.
Option 3: Create a symlink to site-packages
Another permanent approach is to link the Tkinter.py file to Python’s site-packages directory (where it expects modules to live):
sudo ln -s /usr/lib/python2.7/lib-tk/Tkinter.py /usr/lib/python2.7/site-packages/
This makes Python recognize Tkinter as a standard installed module.
3. Check if you missed tk/tcl development packages
If you compiled Python 2.7.14 from source (instead of using the system package), you might have skipped installing the tk/tcl development headers. Install them first:
sudo apt-get update && sudo apt-get install tk-dev tcl-dev
Then recompile Python with Tkinter support enabled:
cd /path/to/your/python-2.7.14/source ./configure --prefix=/usr/local/python27 --with-tcl=/usr/lib/tcl8.5 --with-tk=/usr/lib/tk8.5 make && sudo make install
Ubuntu 16.04 ships with Tcl/Tk 8.5 by default, so the paths above should be correct.
4. Verify the fix
Test if Tkinter works by running this in your terminal:
python2.7 -c "import Tkinter; print('Tkinter imported successfully!')"
If you see the success message, you’re all set.
内容的提问来源于stack exchange,提问作者DavidS

