ubuntu 16.4上的tkinter导入错误

问题描述 投票:4回答:1

我试图运行一个使用乌龟绘制树的代码。代码没有问题因为我在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 python-3.x ubuntu tkinter
1个回答
1
投票

在帖子的底部你会说:

请注意,我在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

© www.soinside.com 2019 - 2024. All rights reserved.