导入tkinter与tk和tkinter导入之间的差异 [英] Difference between import tkinter as tk and from tkinter import

查看:305
本文介绍了导入tkinter与tk和tkinter导入之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是一个愚蠢的问题,但我刚开始学习python而且我对python没有很好的了解。我的问题是来自Tkinter import *

 之间有什么区别? p $ p> 

 将Tkinter导入为tk 

?为什么我不能写

  import Tkinter 

任何人都可以花几分钟来启发我吗?

$ t $ b

解决方案

来自Tkinter import * 将Tkinter中的每个公开对象导入当前命名空间。
import Tkinter 在命名空间中导入namespaceTkinter,
导入Tkinter为tk 做同样的事情,但在本地重命名为'tk'以节省你输入



假设我们有一个模块foo,包含类A,B和C 。



然后 import foo 可以访问foo.A,foo.B和foo.C. / p>

当您执行导入foo为x 时,您也可以访问这些,但名称为xA,xB和XC $ f $ b 来自foo import * 将直接在当前命名空间中导入A,B和C,因此您可以使用A,B和C访问它们。



还有来自foo import A,C 将导入A和C,而不是B导入当前的命名空间。



你也可以从foo导入B做作为Bar ,这将使B名为Bar(在你当前的命名空间。)



所以一般来说:当你只想要一个模块的一个对象时,你从模块导入对象 c>或来自模块导入对象whatiwantittocall



当你想要一些模块功能时,你做导入模块导入模块作为短名称以节省您的输入。



> ,因为您可能会意外地隐藏(覆盖)名称,并且可能会丢失哪些对象属于哪个模块。


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?

解决方案

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.

这篇关于导入tkinter与tk和tkinter导入之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆