【发布时间】:2021-07-18 21:20:18
【问题描述】:
短版:Python 3 无法在我的 iMac 上使用 tkinter。
详细信息和有用信息:我使用的是 macOS Mojave,版本 10.14.3 (18D109)。 (由于软件无法在较新版本上运行,我暂时无法升级。)
在我的脚本中,我使用的是#!/usr/bin/env python3,当我到达import tk as tkinter 行时,我收到了这个错误:
Traceback (most recent call last):
File "/Users/hal/Documents/Dev/HalPy/TestScript.py", line 5, in <module>
import tkinter
File "/Users/hal/.pyenv/versions/3.7.3/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 并获得了 Python shell 和版本信息 (Python 3.7.3 (default, Apr 11 2020, 02:53:05))。然后我尝试了import tkinter as tk,我得到了这个:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/hal/.pyenv/versions/3.7.3/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'
当我进入帮助模式并输入modules 时,我看到了该模块,并且 tkinter 出现在模块列表中。以防万一,我尝试使用 pip 安装它,但它无法安装(这是我的预期)。
那么我需要做什么才能让 Python 3 识别 tkinter? (以防万一,带有 Tkinter 的 Python 2 确实可以工作。)
另外,我查看了this question 和this one,这不是重复的。 (首先请注意,两者都没有公认的答案。)第一个涉及重新安装,重点似乎在 Windows 上,这是在 macOS 上,其中包括预安装的。我有点担心重新安装它会做什么。第二个问题有问题,因为它是在 XCode 框架内运行的,问题的一个因素是错误的 shebang,我已经在使用答案建议的那个。
【问题讨论】:
-
见here
-
尝试运行
brew install tcl-tk brew link tcl-tk --force -
@RocketNikita:我这样做了,但收到一条错误消息,告诉我使用 echo 在我的 .bash_profile 中添加一行。所以我打开 .bash_profile 并将指定的路径添加到我设置 $PATH 的位置,并打开一个新的 shell,该 shell 将在 $PATH 中包含该路径。它仍然给我同样的错误 - 所以路径在那里并且它抱怨它不是。
-
@PaulRooney 是我,还是新安装程序只将新版本的 Python 放在 /Applications 中,而没有更新 /bin 或 /usr/bin 或类似位置中的任何 Python 版本?这就是我正在寻找的。它包括 Python Launcher,因此我必须将每个脚本中的 shebang 更改为指向 /Applications/Python/Contents/MacOS/Python Launcher。
-
对不起,我不知道。我是 Windows/Linux 用户。只是希望链接会有所帮助。下面的答案之一是引用它。