pyenv 安装的 python 版本缺少 tkinter 报错 import _tkinter # If this fails your Python xxx

一、简介

  • 使用 tkinter 生成页面的时候报错:

    perl 复制代码
    Traceback (most recent call last):
      File "/Users/xxx/Desktop/Project/python/duanju_python_pczs/gui.py", line 20, in <module>
        import tkinter as tk
      File "/Users/xxx/.pyenv/versions/3.11.0/lib/python3.11/tkinter/__init__.py", line 38, in <module>
        import _tkinter # If this fails your Python may not be configured for Tk
        ^^^^^^^^^^^^^^^
    ImportError: dlopen(/Users/xxx/.pyenv/versions/3.11.0/lib/python3.11/lib-dynload/_tkinter.cpython-311-darwin.so, 0x0002): Library not loaded: /opt/homebrew/opt/tcl-tk/lib/libtk8.6.dylib
      Referenced from: <E1D3F9E7-858B-3AC7-9D7B-9827F56D3FEF> /Users/xxx/.pyenv/versions/3.11.0/lib/python3.11/lib-dynload/_tkinter.cpython-311-darwin.so
      Reason: tried: '/opt/homebrew/opt/tcl-tk/lib/libtk8.6.dylib' (no such file), '/System/Volumes/Preboot/Cryptexes/OS/opt/homebrew/opt/tcl-tk/lib/libtk8.6.dylib' (no such file), '/opt/homebrew/opt/tcl-tk/lib/libtk8.6.dylib' (no such file), '/opt/homebrew/Cellar/tcl-tk/9.0.2/lib/libtk8.6.dylib' (no such file), '/System/Volumes/Preboot/Cryptexes/OS/opt/homebrew/Cellar/tcl-tk/9.0.2/lib/libtk8.6.dylib' (no such file), '/opt/homebrew/Cellar/tcl-tk/9.0.2/lib/libtk8.6.dylib' (no such file)
  • 原因是:

    当前的 Python 是用 pyenv 装的,但系统里没有它期望版本的 tcl-tk (8.6),只装了 tcl-tk 9.x,导致 _tkinter 动态库加载失败。

二、Mac 解决方案

  • 使用 brew 搜索 $ brew search tcl-tk 并安装 brew install tcl-tk@8

  • 配置环境变量

    sh 复制代码
    $ open ~/.zshrc

    不推荐是 /opt/homebrew/Cellar/tcl-tk@8/ 目录下的,推荐使用 /opt/homebrew/opt/tcl-tk@8/ 目录下的:

    sh 复制代码
    export PATH="/opt/homebrew/opt/tcl-tk@8/bin:$PATH"
    export LDFLAGS="-L/opt/homebrew/opt/tcl-tk@8/lib"
    export CPPFLAGS="-I/opt/homebrew/opt/tcl-tk@8/include"
    export PKG_CONFIG_PATH="/opt/homebrew/opt/tcl-tk@8/lib/pkgconfig"

    报错后执行:

    sh 复制代码
    $ source ~/.zshrc
  • 然后需要重装 python 版本,⚠️ 不重装 Python 是没用的,_tkinter 是编译期决定的

    sh 复制代码
    $ pyenv uninstall 3.11.0
    $ pyenv install 3.11.0

    当然也有临时补丁方案,配置的环境变量不同,但是不能一劳永逸。

  • 重新安装好后,重新运行项目即可。

二、Windows 解决方案

  • 暂时没遇到,遇到再补充....
相关推荐
deephub7 小时前
告别脆弱的单体应用,用多智能体网络构建稳定的生产力工具
人工智能·python·大语言模型·多智能体
烟雨江南aabb7 小时前
Python第六弹:python爬虫篇:什么是爬虫
开发语言·爬虫·python
MomentYY7 小时前
第 1 篇:Agent 到底是什么?别被概念唬住了
人工智能·python·agent
Python大数据分析@7 小时前
对你而言, Vibe Coding 的乐趣是什么?
python
WL_Aurora7 小时前
Python 算法基础篇之排序算法(一):冒泡、选择、插入
python·算法·排序算法
龙腾AI白云7 小时前
中国人工智能培训网—AI系列录播课
python·beautifulsoup
AI算法沐枫7 小时前
大一学生如何入门机器学习,深度学习,学习顺序如何?
人工智能·python·深度学习·学习·线性代数·算法·机器学习
用户6757049885027 小时前
Python 统一大业:uv 如何整合 Pip、Pyenv 和 Venv?
后端·python
SilentSamsara7 小时前
运算符重载:让自定义对象支持 +、[]、in 操作
开发语言·python·算法·青少年编程·pycharm
wuxinyan1237 小时前
工业级大模型学习之路020:LangChain零基础入门教程(第三篇):提示词工程与提示模板系统
人工智能·python·学习·langchain