[Python] from tkinter import * ImportError: No module named tkinter

Posted in :

寫好的程式在別人的電腦裡執行會出錯,我的環境是 macOS 10.14 別人的是 macOS 10.10, 出錯的畫面:

No module named tkinter

網路上查到的解法:

The root of the problem is that the Tkinter module is named Tkinter (capital “T”) in python 2.x, and tkinter (lowercase “t”) in python 3.x.

To make your code work in both Python 2 and 3 you can do something like this:

try:
    # for Python2
    from Tkinter import *
except ImportError:
    # for Python3
    from tkinter import *

However, PEP8 has this to say about wildcard imports:

Wildcard imports ( from <module> import * ) should be avoided

In spite of countless tutorials that ignore PEP8, the PEP8-compliant way to import would be something like this:

import tkinter as tk

When importing in this way, you need to prefix all tkinter commands with tk. (eg: root = tk.Tk(), etc). This will make your code easier to understand at the expense of a tiny bit more typing. Given that both tkinter and ttk are often used together and import classes with the same name, this is a Good Thing. As the Zen of python states: “explicit is better than implicit”.

Note: The as tk part is optional, but lets you do a little less typing: tk.Button(...) vs tkinter.Button(...)


如果你有使用 tkinter 請服用下面的 code 讓程式在 python2 & python3 都可以run:

try:
# for Python2
from Tkinter import *
import ttk
import tkMessageBox as messagebox
except ImportError:
# for Python3
from tkinter import *
from tkinter import ttk
from tkinter import messagebox

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *