Search code examples
python-3.xtkintervirtualenvrhel

RHEL7 import tkinter failed inside virtualenv


On Redhat 7 and python3.6

I can import tkinter without any error:

Python 3.6.5 (default, Jul 25 2018, 21:22:33)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import tkinter
>>>

Within a fresh virtualenv

Python 3.6.4 (default, Jul 20 2018, 12:22:32)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import tkinter
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/ocr1/CRNN_Tensorflow/tkinter/__init__.py", line 36, in <module>
    import _tkinter # If this fails your Python may not be configured for Tk
ModuleNotFoundError: No module named '_tkinter'
>>>

P.S. It's an entire new virtualenv, created by virtualenv <name_of_env> command.


Solution

  • 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/