tcfh2016
tcfh2016

Reputation: 51

Why do I need to import tkinter.messagebox but don't need to import tkinter.Tk() after importing tkinter?

There was one error:

AttributeError: module 'tkinter' has no attribute 'messagebox'

Even the import tkinter already given at the beginning. Why is there no error for the tkinter.Tk()statement?

I have figured that the import statement is not like the #include statement in the C language, so I can understand we need to import tkinter.messagebox if we want to use it even the import tkinter has been given, but what confused me was why the tkinter.Tk can work well even though we didn't write something like import tkinter.Tk?

import time, sys
import tkinter
#import tkinter.messagebox

window = tkinter.Tk()
tkinter.messagebox.showwarning()
window.mainloop()

Upvotes: 4

Views: 3139

Answers (2)

Aran-Fey
Aran-Fey

Reputation: 43156

TL;DR: Because tkinter.messagebox is a module, but tkinter.Tk is a class.


When you do import some_module, python looks for a file or directory named some_module to import. If some_module is a file, that file is executed. If some_module is a directory (i.e. a package, like tkinter is) some_module/__init__.py is executed. The module then contains all those variables (classes, functions, etc) that were defined in __init__.py and nothing else. If there are any sub-modules in this package (like tkinter.messagebox), python doesn't automatically import them. That is why tkinter.messagebox doesn't exist until you import it.

For illustration purposes, here's what the tkinter module's structure could look like:

tkinter/
    __init__.py
    messagebox.py
    tk.py

__init__.py:

from .tk import Tk

tk.py:

class Tk:
    ...

With a setup like this, doing import tkinter will automatically import the Tk class and make it available as tkinter.Tk. But messagebox.py won't be imported automatically - you have to do that manually.

(P.S.: If __init__.py contained the code from . import messagebox, then import tkinter.messagebox wouldn't be necessary.)

Upvotes: 3

funie200
funie200

Reputation: 3908

The tkinter.Tk() function is part of tkinter. However the messagebox function is part of tkinter.messagebox which is another module in tkinter. That's why tkinter.Tk() will work just fine with only tkinter being imported but tkinter.messagebox needs the messagebox module to be imported.

More on the Tkinter modules can be found on the official documentation.

You can get it to work if you either:

from tkinter import messagebox

And then call the function like:

messagebox.showwarning()

Or by importing like you commented in your code out:

import tkinter.messagebox

And calling like you do:

tkinter.messagebox.showwarning()

I hope this helps.

Upvotes: 3

Related Questions