我试着运行一个代码,用海龟画一棵树。代码没有问题,因为我在Windows 10上成功地运行了它,但是在Ubuntu上遇到了以下错误:
mosharraf@mmh:~$ cd Desktop
mosharraf@mmh:~/Desktop$ python3 Tree.py
Traceback (most recent call last):
File "Tree.py", line 6, in <module>
import turtle
File "/usr/local/lib/python3.6/turtle.py", line 107, in <module>
import tkinter as TK
File "/usr/local/lib/python3.6/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'
mosharraf@mmh:~/Desktop$然后我试着安装tkinter,但失败了。
mosharraf@mmh:~$ sudo apt-get install python3-tk
[sudo] password for mosharraf:
Reading package lists... Done
Building dependency tree
Reading state information... Done
python3-tk is already the newest version (3.5.1-1).
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
mosharraf@mmh:~$之后,我检查了目录中的tkinter并找到了它。
mosharraf@mmh:/usr/local/lib/python3.6$ cd tkinter
mosharraf@mmh:/usr/local/lib/python3.6/tkinter$ ls
colorchooser.py constants.py dnd.py font.py __main__.py __pycache__ simpledialog.py tix.py
commondialog.py dialog.py filedialog.py __init__.py messagebox.py scrolledtext.py test ttk.py
mosharraf@mmh:/usr/local/lib/python3.6/tkinter$ python3
Python 3.6.4 (default, Dec 22 2017, 18:44:45)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import tkinter
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.6/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'
>>> 如上面所示,tkinter在目录中,但我不能导入它。我尝试了几种方法,比如
import tkinter
import tkinter as tk
from tkinter import *等。
注意,我在python2.7中运行了代码,它成功地运行了。我还在Windows 10,Python3.6上运行了代码。但在Ubuntu,这是造成问题的原因。
发布于 2017-12-28 20:51:15
在你的帖子底部,你说:
注意,我在python2.7中运行了代码,它成功地运行了。
当您从Python 2导入Tkinter时,您必须说:
import Tkinter
当您从Python 3导入Tkinter时,您必须说:
import tkinter
当我知道我的脚本将从Python的多个版本运行时,我为Tkinter使用的一个片段如下:
import sys
py_version = int(sys.version[0])
# If the python version is lower than 3, use Python 2 import
if py_version < 3:
import Tkinter
# Otherwise use Python 3 import
else:
import tkinter如果上面没有解决您的问题:
我看到你的一条错误信息上面写着
python3-tk is already the newest version (3.5.1-1).
但是错误消息还说您的Python是3.6。
尝试使用:sudo apt-get install python3.6-tk
https://stackoverflow.com/questions/48012086
复制相似问题