TKinter in a Virtualenv
I am using python2.7 with a virtualenv on a machine running linux mint. I received the exact same error as mentioned by the OP when running an application that required matplotlib in my virtualenv. "ImportError: No module named _tkinter, please install the python-tk package"
I ended up deleting and recreating my virtual environment using the suggestions in the above posts. Here are my steps:
- if your virtual environment is activated, then run this command to freeze the requirements to a file that you can access later:
pip freeze > requirements.txt
- if your virtual environment is activated, then deactivate it using:
deactivate
- delete your virtualenv folder.
- install python-tk using:
sudo apt-get install python-tk
- recreate your virtualenv using:
virtualenv <nameofyourenv> --system-site-packages
- next, activate your virtualenv:
source <virtual environment folder>/bin/activate
- restore all your packages that you froze earlier from the requirements.txt file:
pip install -r <path to requirements.txt file>
now, when I run the same code as before, it has no problem importing _tkinter. Hope this helps! Thanks to the everyone's suggestions above. It really helped me a lot.
Set the environment variable TCL_LIBRARY in your activate
script. On Windows (Python 2.7 with Tcl 8.5), just add this line to Scripts\activate.bat
:
set "TCL_LIBRARY=C:\Python27\tcl\tcl8.5"
@Jasper van den Bosch's edit: On Ubuntu, the modification to the script activate
is the following:
TK_LIBRARY=/usr/lib/python2.7/lib-tk:/usr/lib/python2.7/site-packages/PIL:/usr/lib
TKPATH=/usr/lib/python2.7/lib-tk:/usr/lib/python2.7/site-packages/PIL:/usr/lib
TCL_LIBRARY=/usr/lib
export TCL_LIBRARY TK_LIBRARY TKPATH
The reference of this can be found on this question on askubuntu
I manage to integrate tkinter
in python3 to virtualenv by symlink tkinter
folder to virtualenv python3
. I works for me. But I don't know if it's the right way.
- install tkinter
sudo apt-get install python3-tk
- go to your virtualenv's python lib folder
cd ~/.virtualenvs/cv/lib/python3.4/
- link the tkinter
ln -s /usr/lib/python3.4/tkinter tkinter
Hope this helps.
In later versions of python, this may result in a
ModuleNotFoundError: No module named '_tkinter'
In this case, ensure to also symlink/usr/lib/python3.x/lib-dynload/_tkinter.cpython-36m-x86_64-linux-gnu.so
as
path/to/virtualenv/lib/python3.x/lib-dynload/_tkinter.cpython-36m-x86_64-linux-gnu.so
using
ln -s /usr/lib/python3.x/lib-dynload/_tkinter.cpython-36m-x86_64-linux-gnu.so _tkinter.cpython-36m-x86_64-linux-gnu.so
from within your virtualenv lib/python3.x/lib-dynload/
directory.