[英]tkinter import error on ubuntu 16.4
我试图运行一个使用乌龟画一棵树的代码。 代码没有问题,因为我在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 *
等等
请注意,我在python 2.7中运行了代码,并且运行成功。 我还在Windows 10 Python 3.6上运行了代码。 但是在Ubuntu中,这会引起问题。
在帖子的底部,您说:
请注意,我在python 2.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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.