The difference between importing tkinter as tk and from tkinter import

I know this is a stupid question, but I'm just starting to learn python and I don't have a good knowledge of python. My question is what is the difference between

from Tkinter import * 

and

 import Tkinter as tk 

Why can't I just write

 import Tkinter 

Can someone leave a few minutes to enlighten me?

+6
source share
2 answers

from Tkinter import * imports every open object in Tkinter into the current namespace. import Tkinter imports the import Tkinter namespace into your namespace and import Tkinter as tk does the same, but renames it locally to tk to save text input

let's say we have a module foo containing classes A, B and C.

Then import foo gives you access to foo.A, foo.B and foo.C.

When you execute import foo as x , you have access to them too, but under the names xA, xB and xC from foo import * will import A, B and C directly into your current namespace so that you can access them with A, B and C.

There is also from foo import A, C , which will import A and C, but not B, into your current namespace.

You can also make from foo import B as Bar , which will make B available under the name Bar (in your current namespace).

So, usually: when you want only one module object, you do from module import object or from module import object as whatiwantittocall .

If you need some modules, you can do import module or import module as shortname to save the input.

from module import * not recommended, since you can accidentally stub ("override") names and can lose track of which objects belong to this module.

+11
source

you can use

 import Tkinter 

However, if you do, you will need to prefix each Tk class name that you use with Tkinter. .

This is rather inconvenient.

On the other hand, the following:

 import Tkinter as tk 

fixes the problem by only requiring you to type tk. instead of Tkinter. .

Concerning:

 from Tkinter import * 

This is usually a bad idea for the reasons discussed in Should importing wildcards be avoided?

+3
source

All Articles