[英]Why does from tkinter import * not import Tkinter's messagebox?
I am learning Python, and as I try some code using tkinter I hit this issue:我正在学习 Python,当我使用 tkinter 尝试一些代码时,我遇到了这个问题:
I import all the definitions of tkinter with the line:我使用以下行导入 tkinter 的所有定义:
from tkinter import *
Then I try to open a message box:然后我尝试打开一个消息框:
messagebox.showinfo(message='My message')
But when I run the program, if this line must be executed, I get the message:但是当我运行程序时,如果必须执行此行,我会收到以下消息:
Traceback (most recent call last):
File ...
...
NameError: name 'messagebox' is not defined
If I add to the import line an explicit import for messagebox:如果我向导入行添加消息框的显式导入:
from tkinter import *
from tkinter import messagebox
it works, but I don't understand the reason why I have to add this import.它有效,但我不明白为什么我必须添加这个导入。
messagebox
is a module , eg messagebox.py
. messagebox
是一个 模块,例如messagebox.py
。 This is not automatically imported into the namespace when you from tkinter import *
.当您from tkinter import *
时,这不会自动导入命名空间。 What is automatically imported is what tkinter.__init__
defines as __all__
:自动导入的是tkinter.__init__
定义为__all__
:
__all__ = [name for name, obj in globals().items()
if not name.startswith('_') and not isinstance(obj, types.ModuleType)
and name not in {'wantobjects'}]
Notice that tkinter even explicitly excludes anything that is types.ModuleType
, which messagebox
falls under.请注意, tkinter 甚至明确排除了types.ModuleType
的任何内容,该messagebox
属于该消息框。
When in doubt about this type of thing, you can always check out the CPython tkinter Python lib itself .如果对这类事情有疑问,您可以随时查看 CPython tkinter Python lib 本身。
The Python docs' Importing * From a Package contain more detail. Python 文档的Importing * From a Package包含更多详细信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.