Las versiones de Python instaladas a través de pyenv no pueden importar tkinter
:
※ python Python 3.8.1 (default, Feb 29 2020, 11:45:59) [Clang 11.0.0 (clang-1100.0.33.17)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import tkinter Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/factor/.pyenv/versions/3.8.1/lib/python3.8/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' >>>
o puede recibir un mensaje sobre la versión del encabezado que no coincide con el binario:
DEPRECATION WARNING: The system version of Tk is deprecated and may be removed in a future release. Please don't rely on it. Set TK_SILENCE_DEPRECATION=1 to suppress this warning. Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/factor/.pyenv/versions/3.8.1/lib/python3.8/tkinter/__init__.py", line 4552, in _test root = Tk() File "/Users/factor/.pyenv/versions/3.8.1/lib/python3.8/tkinter/__init__.py", line 2263, in __init__ self._loadtk() File "/Users/factor/.pyenv/versions/3.8.1/lib/python3.8/tkinter/__init__.py", line 2279, in _loadtk raise RuntimeError("tk.h version (%s) doesn't match libtk.a version (%s)" RuntimeError: tk.h version (8.6) doesn't match libtk.a version (8.5)
TL; DR establece el env. vars. mencionado en las advertencias de tcl-tk
y este comentario de GitHub al instalar nuevos Pythons a través de pyenv para obtener tkinter
.
Primero, asegúrese de tener el último tcl-tk
a través de homebrew y luego preste atención a sus advertencias:
※ brew install tcl-tk ※ brew info tcl-tk tcl-tk: stable 8.6.10 (bottled) [keg-only] ... ==> Caveats tcl-tk is keg-only, which means it was not symlinked into /usr/local, because tk installs some X11 headers and macOS provides an (older) Tcl/Tk. If you need to have tcl-tk first in your PATH run: echo 'export PATH="/usr/local/opt/tcl-tk/bin:$PATH"' >> ~/.zshrc For compilers to find tcl-tk you may need to set: export LDFLAGS="-L/usr/local/opt/tcl-tk/lib" export CPPFLAGS="-I/usr/local/opt/tcl-tk/include" For pkg-config to find tcl-tk you may need to set: export PKG_CONFIG_PATH="/usr/local/opt/tcl-tk/lib/pkgconfig" ...
También necesitará saber acerca de PYTHON_CONFIGURE_OPTS de PYTHON_CONFIGURE_OPTS
, --with-tcltk-includes
y --with-tcltk-libs
, por ejemplo, de este comentario .
A continuación, reinstale Python con las variables de entorno activas:
※ pyenv uninstall 3.8.1 ※ env \ PATH="$(brew --prefix tcl-tk)/bin:$PATH" \ LDFLAGS="-L$(brew --prefix tcl-tk)/lib" \ CPPFLAGS="-I$(brew --prefix tcl-tk)/include" \ PKG_CONFIG_PATH="$(brew --prefix tcl-tk)/lib/pkgconfig" \ CFLAGS="-I$(brew --prefix tcl-tk)/include" \ PYTHON_CONFIGURE_OPTS="--with-tcltk-includes='-I$(brew --prefix tcl-tk)/include' --with-tcltk-libs='-L$(brew --prefix tcl-tk)/lib -ltcl8.6 -ltk8.6'" \ pyenv install 3.8.1
Debería funcionar ahora:
※ pyenv global 3.8.1 ※ python Python 3.8.1 (default, Feb 29 2020, 11:56:10) [Clang 11.0.0 (clang-1100.0.33.17)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import tkinter >>> tkinter.TclVersion, tkinter.TkVersion (8.6, 8.6) >>> tkinter._test() # You should get a GUI
Si recibe el siguiente error, es posible que se esté perdiendo el PYTHON_CONFIGURE_OPTS
. variedad encima.
DEPRECATION WARNING: The system version of Tk is deprecated and may be removed in a future release. Please don't rely on it. Set TK_SILENCE_DEPRECATION=1 to suppress this warning. Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/factor/.pyenv/versions/3.8.1/lib/python3.8/tkinter/__init__.py", line 4552, in _test root = Tk() File "/Users/factor/.pyenv/versions/3.8.1/lib/python3.8/tkinter/__init__.py", line 2263, in __init__ self._loadtk() File "/Users/factor/.pyenv/versions/3.8.1/lib/python3.8/tkinter/__init__.py", line 2279, in _loadtk raise RuntimeError("tk.h version (%s) doesn't match libtk.a version (%s)" RuntimeError: tk.h version (8.6) doesn't match libtk.a version (8.5)
Aquí hay una guía paso a paso para hacer que tkinter
(e IDLE) funcione si usa pyenv
para la administración de entornos de Python en macOS:
tcl-tk
con Homebrew. En shell, ejecute brew install tcl-tk
echo 'export PATH="/usr/local/opt/tcl-tk/bin:$PATH"' >> ~/.zshrc
Terminal
o ejecutando source ~/.zshrc
tck-tk
esté en $PATH
. Ejecute echo $PATH | grep --color=auto tcl-tk
. Como resultado, debería ver su contenido de $PATH con tcl-tk
resaltadoexport LDFLAGS="-L/usr/local/opt/tcl-tk/lib"
export CPPFLAGS="-I/usr/local/opt/tcl-tk/include"
export PKG_CONFIG_PATH="/usr/local/opt/tcl-tk/lib/pkgconfig"
pyenv
, desinstálela con pyenv uninstall <your python version>
. Por ejemplo pyenv uninstall 3.8.2
python-build
. En shell, ejecute PYTHON_CONFIGURE_OPTS="--with-tcltk-includes='-I/usr/local/opt/tcl-tk/include' --with-tcltk-libs='-L/usr/local/opt/tcl-tk/lib -ltcl8.6 -ltk8.6'"
Nota: en el futuro, use la versión tck-tk
que realmente se instaló con Homebrew. En el momento de publicar 8.6
era el realpyenv
con pyenv install <version>
. Por ejemplo pyenv install 3.8.2
Prueba
pyenv global <verion that you've just installed>
idle
. Debería ver la ventana IDLE sin advertencias y "texto impreso en rojo".tkinter
. En shell, ejecute python -m tkinter -c "tkinter._test()"
. Debería ver una ventana de prueba como en la imagen:¡Eso es todo!
Mi entorno:
compruebe que algo salió mal al ejecutar los pasos anteriores:
zsh
(incluido en macOS Catalina) = "shell" arribapyenv
(instalado con Homebrew y PATH actualizado según el archivo Léame oficial de pyenv
de GitHub)3.8.x
- 3.9.x
(instalado con pyenv install <version>
)Para Python 3.9 y versiones superiores, puede usar la siguiente fórmula
preparar la instalación python-tk@3.9
Instalará python@3.9 y tcl-tk y los vinculará por usted.
Tuve el mismo problema cuando intenté instalar tkinter
a través de pyenv. Pude solucionarlo usando lo siguiente en caso de que alguien tenga el mismo problema y aún quiera seguir con pyenv
.
La solución
Seguí las instrucciones de @nickolay para instalar tkinter
y configurar la ruta de la manera adecuada.
Luego, instalé anaconda3-2020.07 usando el comando pyenv install anaconda3-2020.07
.
Porque estoy usando pyenv python 3.8.6 globalmente : navegué a la carpeta que quiero usar tkinter y usé anaconda3-2020.07
localmente usando el comando pyenv local anaconda3-2020.07
para usar esta versión de pyenv en esa carpeta específica. ¡Funcionó sin errores!
Nota: estoy usando el siguiente script en .bash_profile
para activar virtualenv automáticamente cuando cd el directorio deseado
# manage python version using pyenv if command -v pyenv 1>/dev/null 2>&1; then eval "$(pyenv init -)" fi # add pyenv virtualenv eval "$(pyenv virtualenv-init -)"
Para MacOS Big Sur (11.2.3), la respuesta de Carl G no me funcionó porque recibí un error de zlib. Partiendo de esta respuesta y esta publicación de blog , encontré el éxito con
brew install bzip2 export LDFLAGS="-L $(xcrun --show-sdk-path)/usr/lib -L brew --prefix bzip2/lib" export CFLAGS="-L $(xcrun --show-sdk-path)/usr/include -L brew --prefix bzip2/include" export PYTHON_CONFIGURE_OPTS="--with-tcltk-includes='-I/usr/local/opt/tcl-tk/include' --with-tcltk-libs='-L/usr/local/opt/tcl-tk/lib -ltcl8.6 -ltk8.6' --enable-framework" pyenv install 3.8.6