60
37

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

pyenvのpythonでtkinterを使用する方法

Last updated at Posted at 2019-11-01

Issue

pyenvでinstallしたpythonでpython -m tkinterimport tkinterをしたときに以下のエラーが発生。
ネット上の記事を見ると、brew install tcl-tkで治るなど書いてあったが、上手くいかなかった。
しかし、どうやら最近リリースされたpyenvのv1.2.14でtcl-tkとの互換性が修正されたらしく、GitHubのissueで解決策も書いてあったのでシェアします。

Traceback (most recent call last):
  File "/Users/ken/.pyenv/versions/3.7.4/lib/python3.7/runpy.py", line 183, in _run_module_as_ma
in
    mod_name, mod_spec, code = _get_module_details(mod_name, _Error)
  File "/Users/ken/.pyenv/versions/3.7.4/lib/python3.7/runpy.py", line 142, in _get_module_detai
ls
    return _get_module_details(pkg_main_name, error)
  File "/Users/ken/.pyenv/versions/3.7.4/lib/python3.7/runpy.py", line 109, in _get_module_detai
ls
    __import__(pkg_name)
  File "/Users/ken/.pyenv/versions/3.7.4/lib/python3.7/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'

Solution

  • Upgrade pyenv (>=1.2.14)
brew upgrade pyenv
  • Install tcl-tk
brew install tcl-tk
  • Set environment variables

    • If you use bash

      bash_profile

    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'"

    
    - If you use fish
    
        ```shell:config.fish
    set -x PATH "/usr/local/opt/tcl-tk/bin" $PATH
    set -x LDFLAGS "-L/usr/local/opt/tcl-tk/lib"
    set -x CPPFLAGS "-I/usr/local/opt/tcl-tk/include"
    set -x PKG_CONFIG_PATH "/usr/local/opt/tcl-tk/lib/pkgconfig"
    set -x 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'"
    
  • Reinstall python via pyenv

pyenv install 3.7.4
  • Run tkinter
python -m tkinter
  • Solved :beer:

Reference

60
37
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
60
37

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?