import tkinter as tk 和 from tkinter import 的区别 [英] Difference between import tkinter as tk and from tkinter import

查看:439
本文介绍了import tkinter as tk 和 from tkinter import 的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是一个愚蠢的问题,但我才刚刚开始学习 Python,而且我对 Python 没有很好的了解.我的问题是

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 *

import Tkinter as tk

?为什么我不能直接写

import Tkinter

有人能抽出几分钟来启发我吗?

Could anyone spare a few mins to enlighten me?

推荐答案

from Tkinter import * 将 Tkinter 中每个暴露的对象导入到您当前的命名空间中.import Tkinter 在您的命名空间中导入命名空间"Tkinter 并import Tkinter as tk 做同样的事情,但将它在本地重命名"为 'tk' 以节省您的输入

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

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

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

然后 import foo 使您可以访问 foo.A、foo.B 和 foo.C.

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

当您执行 import foo as x 时,您也可以访问它们,但名称为 x.A、x.B 和 x.C.from foo import * 将直接在你当前的命名空间中导入 A、B 和 C,因此你可以使用 A、B 和 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.

还有 from foo import A, C 将导入 A 和 C,但不会将 B 导入您当前的命名空间.

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

您还可以执行 from foo import B as Bar,这将使 B 在名称 Bar 下可用(在您当前的命名空间中).

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

所以一般来说:当你只需要一个模块的一个对象时,你可以使用 from module import objectfrom module import object as whatiwantittocall.

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

当您需要某些模块功能时,您可以执行 import moduleimport module as shortname 以节省输入.

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

from module import * 是不鼓励的,因为您可能会不小心遮蔽(覆盖")名称,并且可能会忘记哪些对象属于哪个模块.

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

这篇关于import tkinter as tk 和 from tkinter import 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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