【问题标题】:Unable to import tkinter in Python3, but it works in python2 (Python3.7 macOS Catalina)无法在 Python3 中导入 tkinter,但它在 python2 中有效(Python3.7 macOS Catalina)
【发布时间】:2020-10-27 20:15:58
【问题描述】:

运行python3 将我带入python,然后简单地运行import tkinter 会导致以下错误:

File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.7/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'

但是,当进入 python shell(不是 python3)时,import tkinter 可以正常工作。如何让 tkinter 使用 Python3?

请注意以下几点:

  • 我在 MacOS Catalina 上
  • 我正在使用 Python 3.7.3(基于 python3 --version
  • 看起来我的 python3 可执行文件是 (/usr/bin/python3)
  • tkinter 的路径是/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/tkinter/
  • 我可以在终端中运行idle,但我不能运行idle3
  • 我认为我没有使用 virtualenvpyenv 或类似的东西

【问题讨论】:

  • /Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.7/Python3 中的 python3 可执行文件导致exec format error

标签: python python-3.x tkinter python-import python-3.7


【解决方案1】:

您需要单独的 Tcl/Tk 安装。从 python.org 尝试更新版本的 Python3 二进制安装程序,它捆绑了 Tcl/Tk。

【讨论】:

    【解决方案2】:

    不要通过idle 安装tkinter。试试idle3。如果没有,请使用您的操作系统安装程序安装python3-tk。 (我有 apt。我在 Debian 上。)。祝你好运!

    【讨论】:

    • 你能澄清你的意思吗?我的终端返回command not found: idle3。如何通过idle3安装tkinter?
    • 我相信你没有安装它。尝试搜索如何安装 idle3?
    【解决方案3】:

    不要在import _tkinter中使用_

    使用import tkinter

    我相信这会奏效。如果可行,请勾选我的答案。

    【讨论】:

    • 我从来没有跑过import _tkinter,我只是跑过import tkinter。通过运行import tkinter,如果Python 无法导入它,它会自动尝试import _tkinter 本身,如果它不能这样做,则会抛出错误。
    • 你在idle或python shell上哪里写代码
    • 终端中的 Python3 shell(终端中的python3 命令,然后尝试从那里运行import tkinter
    【解决方案4】:

    打开命令提示符并运行pip install tkinter 然后打开您的 python 项目并按 Ctrl + S。 然后运行你的项目。 希望我的回答对你有用。

    【讨论】:

    • tkinter 是一个内置模块,所以你不能使用pip。输出:ERROR: No matching distribution found for tkinter
    猜你喜欢
    • 2019-03-30
    • 2012-12-20
    • 2020-05-18
    • 2019-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-30
    • 2020-07-28
    相关资源
    最近更新 更多