簡體   English   中英

ubuntu 16.4上的tkinter導入錯誤

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM