I am learning Python, and as I try some code using tkinter I hit this issue:
I import all the definitions of tkinter with the line:
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, e.g. messagebox.py
. This is not automatically imported into the namespace when you from tkinter import *
. What is automatically imported is what tkinter.__init__
defines as __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.
When in doubt about this type of thing, you can always check out the CPython tkinter Python lib itself.
The Python docs' Importing * From a Package contain more detail.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With