Difference between import tkinter as tk and from tkinter import

跟風遠走 提交于 2019-11-26 14:01:32

问题


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?


回答1:


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.




回答2:


You can certainly use

import Tkinter

However, if you do that, you'd have to prefix every single Tk class name you use with Tkinter..

This is rather inconvenient.

On the other hand, the following:

import Tkinter as tk

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

As to:

from Tkinter import *

it is generally a bad idea, for reasons discussed in Should wildcard import be avoided?




回答3:


Writing:

from tkinter import * 

results in importing everything that exists in tkinter module

Writing:

import tkinter

results in importing tkinter module but if you do so, in order to be able to call any method you will have to use:

tkinter.function_name()


来源:https://stackoverflow.com/questions/15974787/difference-between-import-tkinter-as-tk-and-from-tkinter-import

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!