LoginSignup
1
3

More than 1 year has passed since last update.

【Python3】macのpyenv環境下でtkinterを使えるようにする。

Last updated at Posted at 2021-08-09

はじめに

tkinterをimportしたファイルを実行しようとしたところ...
長文のエラー文が出ました。

file "/usr/local/cellar/python@3.9/3.9.5/frameworks/python.framework/versions/3.9/lib/python3.9/runpy.py", 
line 188, in _run_module_as_main mod_name, mod_spec, code = _get_module_details(mod_name, _error) file 
"/usr/local/cellar/python@3.9/3.9.5/frameworks/python.framework/versions/3.9/lib/python3.9/runpy.py",
 line 147, in _get_module_details return _get_module_details(pkg_main_name, error) file 
"/usr/local/cellar/python@3.9/3.9.5/frameworks/python.framework/versions/3.9/lib/python3.9/runpy.py", line 111, in _get_module_details __import__(pkg_name) file 
"/usr/local/cellar/python@3.9/3.9.5/frameworks/python.framework/versions/3.9/lib/python3.9/tkinter/__init__.py", line 37,
 in <module> import _tkinter 
# if this fails your python may not be configured for tk modulenotfounderror:
 no module named '_tkinter' mac

エラーを省略すると...ModuleNotFoundError: No module named '_tkinter' mac
とりあえず、macはデフォルトではtkinterを使えないようです。
macでtkinterを使えるようにする方法を下記にまとめます。

環境

・macOS Catalina
・Homebrewはインストール済み
・pyenvを使用している
・Python3.9.6
・zsh使用

参考記事

Macのpyenv環境下でtkinterを使えるようにする方法
pyenvでインストールしたpythonでtkinterがimportできなかった時。
【もう迷わない!? mac編】Pyenv環境からTkinterをインストール

解決手順

基本的には上記の参考記事と同じことをしていきます。
そのため詳しくはリンクをご覧ください。

Pythonのアンインストール

% pyenv global system
% pyenv uninstall 3.X.X

↑で、pyenv global systemができない場合はrm ~/.python-versionコマンドを実行する。

tcl-tkのインストール

% brew install tcl-tk
% brew info tcl-tk

↑上記コマンドで表示されたコードをコピーして.zshrcに貼り付けします。

% vi .zshrc
.zshrc
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"

Pythonの再インストール

% 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'" pyenv install 3.X.X

上記参考記事通りにここまで進めて、順調♪と思いきや...

% python -m tkinter

でインストールができているか確認したところ、最初に記載したエラーがまた出ました...
↑ここまでで解決した人はいいのですが、解決しなかった場合について記載していきます。

再解決手順

上記解決手順のPythonのアンインストールを実行します。

次に下記コマンドを実行します。

% brew install python-tk@3.9
% python -c 'import tkinter;print(tkinter.TkVersion);'

最後に、上記のPythonの再インストールを行いましょう。
これでpython -m tkinterを実行するとtkinterが開けました🎉

参考記事
MacOS BigSurはpython3tkinterを使用してエラーを報告します
Why my Python installed via home brew not include Tkinter

最後に

なぜpython-tk@3.9をインストールしないと動かなかったのかはよくわかりませんでした。
ご存知の方いましたら教えていただけますと幸いです。

1
3
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
1
3