RHEL7 import tkinter failed inside virtualenv

醉酒当歌 提交于 2020-04-13 09:00:12

问题


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.


回答1:


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/




回答2:


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:

  1. Install tkinter and any other dependencies in the virtual environment with pip install.
  2. 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



来源:https://stackoverflow.com/questions/51981132/rhel7-import-tkinter-failed-inside-virtualenv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!