Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

python - Difference between import tkinter as tk and from tkinter import

I know it is a stupid question but I am just starting to learn python and i don't have 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

Could anyone spare a few mins to enlighten me?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

from Tkinter import * imports every exposed object in Tkinter into your current namespace. import Tkinter imports the "namespace" Tkinter in your namespace and import Tkinter as tk does the same, but "renames" it locally to 'tk' to save you typing

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

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

When you do import foo as x you have access to those too, but under the names x.A, x.B, and x.C. from foo import * will import A, B, and C directly in your current namespace, so you can access them with A, B, and C.

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

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

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

When you want some modules functionality, you do import module, or import module as shortname to save you typing.

from module import * is discouraged, as you may accidentally shadow ("override") names, and may lose track which objects belong to wich module.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...