RHEL7 import tkinter failed inside virtualenv
I have found out two different ways to solve my problem eventually.
1. Make sure the virtualenv created is using the same python version
From my case above, the python of virtualenv version is Python 3.6.4, but the python version of my machine is actually Python 3.6.5.
Hence, virtualenv <name_of_env>
is created with the lib
of Python 3.6.4. To solve this issue can use
virtualenv -p <PYTHON_EXE>, --python=PYTHON_EXE <name_of_env>
or
virtualenv --python=<PYTHON_EXE> <name_of_env>
to specify the python exe location.
And use the option --system-site-packages
to include system modules. (credit to Rob T. answer above)
2. Copy the package you need from lib
directly
This method actually is a bit tricky. Just go the machine python lib
directory and copy the package you need into virtualenv python lib
directory
e.g.:
cd /usr/lib/python3.6.5
cp -a ./tkinter /my_project/venv/lib/
Since you are using a virtual environment, you start with a "clean" Python environment with none of the system packages. This is what helps make virtual environments isolated, stable, and reproducible.
You have two choices:
- Install tkinter and any other dependencies in the virtual environment with
pip install
. - Use the option
--system-site-packages
when creating the virtual environment to include system modules.
The 2nd option is easier, since you don't need to reinstall anything. However, the first option is preferred especially when you use requirements.txt
and pip freeze
. Then you can easily recreate that virtual environment on another system.
There are some tips that may help you in How to install Python 3, venv, virtualenv, and pipenv on RHEL