When using the Python code found on the Internet, I often encounter the error that this import statement throws:
Importerror:no module named ' xxxx '
For example, in the code I'm looking for, there are a few words:
From Tkinter Import *
Import Tkmessagebox
Result Error:
Importerror:no module named ' Tkinter '
This is most likely because the code found is python2.x, but it runs in a python3.x environment. In fact, the top of the Tkinter library in Python3 has changed its name, became a tkinter, but the first letter to lowercase, but the import statement is case sensitive.
In fact, there is a good way to complete the code from 2.x to 3.x of the conversion, here to the Tkinter library as an example, the following methods:
1. Open the Tkinter Library folder, such as mine is C:\Python34\Lib\tkinter, view its directory structure, the following figure
We can immediately find the structure of the entire library, each module of each library's name at a glance.
2. Change the corresponding import statement, Tkinter to Tkinter, and then
Import Tkmessagebox
Change into
Import Tkinter.messagebox #对应着tkinter文件夹底下的messagebox. py
To be aware of this form, you must write down all the symbols in the following import, or else you will be wrong:
Messagebox.showinfo ("title", "Hello World") #NameError: Name ' MessageBox ' are not defined
Tkinter.messagebox.showinfo ("title", "Hello World") #正确
or change it into
From Tkinter import MessageBox #对应着tkinter文件夹底下的messagebox. py
You can write
Finally add two points to pay attention to the place:
1.packages can be considered a folder, and modules can be viewed as a. py file under a folder, and a variety of import statements boils down to
From Packages1.packages2 import modules1
Or
Import Packages1.packages2.modules1
2.
From Tkinter Import *
Instead of import all the. py files under the Tkinter folder, you are actually just import all the objects in the __init__.py, such as a Tk object in __init__.py, so after using the import statement above, You can refer directly to TK:
root = Tk ()
But if you want to use the object in messagebox.py, you have to quote it honestly:
From Tkinter import MessageBox #对应着tkinter文件夹底下的messagebox. py