tcl-tk (tkinter) 未在 MacOS Mojave 上通过 Homebrew pyenv 安装

Dri*_*ler 3 python homebrew tcl pyenv macos-mojave

如果我在 MacOS Mojave 上使用 Homebrew 执行此操作:

$ brew install tcl-tk
$ brew install pyenv
$ pyenv install 3.7.4
$ pyenv global 3.7.4
$ python -m tkinter -c 'tkinter._test()'    
Run Code Online (Sandbox Code Playgroud)

我得到:

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

我已经搜索了好几天,并尝试了各种解决方案,例如这里,但到目前为止还没有运气。有什么想法为什么我会收到此错误以及如何修复它吗?

提前致谢!

Dad*_*dyM 6

以下是使 IDLE 和工作正常进行的分步指南tkinter

  1. tcl-tk使用 Homebrew安装。在 shell 中运行brew install tcl-tk
  2. 在外壳中运行echo 'export PATH="/usr/local/opt/tcl-tk/bin:$PATH"' >> ~/.zshrc
  3. 通过退出Terminal应用程序或运行来重新加载 shellsource ~/.zshrc
  4. 重新加载后检查是否tck-tk$PATH. 跑步echo $PATH | grep --color=auto tcl-tk。结果你应该看到你的 $PATH 内容tcl-tk突出显示
  5. 现在我们从步骤 #1 的 Homebrew 输出中运行三个命令
    1. 在外壳中运行export LDFLAGS="-L/usr/local/opt/tcl-tk/lib"
    2. 在外壳中运行export CPPFLAGS="-I/usr/local/opt/tcl-tk/include"
    3. 在外壳中运行export PKG_CONFIG_PATH="/usr/local/opt/tcl-tk/lib/pkgconfig"
  6. 如果您已经安装了 Python 版本,pyenv则使用 卸载它pyenv uninstall <your python version>。例如pyenv uninstall 3.8.2
  7. 设置将被使用的环境变量python-build。在 shell 中运行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'" 注意:将来使用tck-tk实际随 Homebrew 安装的版本。发布时的8.6实际情况
  8. 最后使用 with 安装pyenvPython pyenv install <version>。例如pyenv install 3.8.2

测试

  1. 在外壳中运行pyenv global <verion that you've just installed>
  2. 现在检查空闲。在外壳中运行idle. 您应该看到 IDLE 窗口,没有任何警告和“文本以红色打印”。

IDLE 窗口从终端运行。 无警告

  1. 现在检查一下tkinter。在外壳中运行python -m tkinter -c "tkinter._test()". 您应该看到如图所示的测试窗口:

tkinter 测试窗口

就是这样!

我的环境:

检查执行上述步骤是否出了问题:

  1. macOS Catalina
  2. zsh(包含在 macOS Catalina 中)=上面的“shell”
  3. Homebrew(按照Homebrew官网的说明安装)
  4. pyenv(使用 Homebrew 安装,并根据pyenvGitHub 的官方自述文件更新 PATH)
  5. Python 3.8.x- 3.9.x(用命令安装pyenv install <version>