Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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.

like image 508
Pascal Avatar asked Mar 02 '23 15:03

Pascal


1 Answers

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.

like image 154
Brad Solomon Avatar answered Mar 05 '23 19:03

Brad Solomon