Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
like image 308
tcfh2016 Avatar asked Oct 26 '25 06:10

tcfh2016


1 Answers

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.

like image 168
funie200 Avatar answered Oct 28 '25 21:10

funie200



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!