TAGS :Viewed: 7 - Published at: a few seconds ago

[ python import confusion (example: tk mesagebox python3) ]

I'm just beginning to learn tkinter at the moment, and when importing messagebox I found that I must not really understand import statements.

The thing that confuses me is that

import tkinter as tk

def text_box():
    if tk.messagebox.askokcancel("Quit", "Never Mind"):
        root.destroy()

root = tk.Tk()
button = tk.Button(root, text="Press the button", command=text_box)
button.pack()
root.mainloop()

compiles fine, but pressing the button gives the error 'module' object has no attribute 'messagebox' while the code

import tkinter as tk
from tkinter import messagebox

...
    if messagebox.askokcancel("Quit", "Never Mind"):
...

works without a hitch.

I get a similar error if I import with from tkinter import *.

The help for tkinter shows messagebox in the list of PACKAGE CONTENTS, but I just can't load it in the normal way.

So my question is, why? and what is it about importing that I don't understand.

Just thought I should mention - the code only works in python3, and in python2.x messagebox is called tkMessageBox and is not defined in tkinter.

Answer 1


tkinter.messagebox is a module, not a class.

As it isn't imported in tkinter.__init__.py, you explicitly have to import it before you can use it.

import tkinter
tkinter.messagebox  # would raise an ImportError
from tkinter import messagebox
tkinter.messagebox  # now it's available eiter as `messagebox` or `tkinter.messagebox`

Answer 2


try this

import sys

from tkinter import *

... and your code