Install python by pyenv w/ tcl/tk on MacOS 10.14.6 (Mojave)

Azuryn
1 min readDec 18, 2019

--

System info:
macOS 10.14.6 (Mojave), tcl-tk 8.6.9, pyenv 1.2.15, and python 3.8.0.

Issue:

Running python -m tkinter ends up with following error:

ModuleNotFoundError: No module named '_tkinter'

or executing idle gets following error:

** IDLE can't import Tkinter.
Your Python may not be configured for Tk. **

Solution:

0. If python was installed previously, uninstall it first.

1. Install pyenv via homebrew

brew install pyenv

2. Install tcl-tk via homebrew

brew install tcl-tk

3. Add environment variables into ~/.zshrc

# python pyenv
export PATH="$HOME/.pyenv/bin:$PATH"
if which pyenv > /dev/null; then
eval "$(pyenv init -)";
fi
# pyenv-virtualenv
if which pyenv-virtualenv-init > /dev/null; then
eval "$(pyenv virtualenv-init -)";
fi
# tcl-tk
export PATH="/usr/local/opt/tcl-tk/bin:$PATH"
export 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"
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'"

4. Install pyenv-virtualenv via homebrew

brew install pyenv-virtualenv

5. Install python by pyenv (3.8.0 for example)

pyenv install 3.8.0

6. Restart shell

exec $SHELL

7. Create a local environment of python 3.8.0 by pyenv:

mkdir ~/foo; cd ~/foo
pyenv local 3.8.0
pyenv version

8. Test tcl-tk installation with:

python -m tkinter -c 'tkinter._test()'

or simply:

idle

Job done.

references:
https://github.com/pyenv/pyenv/issues/1375#issuecomment-524280004
https://github.com/pyenv/pyenv/issues/1375#issuecomment-549754431

--

--