Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tk messagebox import confusion

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 Python 3, and in Python 2.x messagebox is called tkMessageBox and is not defined in tkinter.

like image 958
Apple Avatar asked May 04 '13 13:05

Apple


People also ask

What are the different types of Messagebox available in message widget of tkinter module?

The tkMessageBox module is used to display message boxes in your applications. This module provides a number of functions that you can use to display an appropriate message. Some of these functions are showinfo, showwarning, showerror, askquestion, askokcancel, askyesno, and askretryignore.

How do I display the error box in Python?

Build A Paint Program With TKinter and Python If you need to display the error messagebox in your application, you can use showerror("Title", "Error Message") method. This method can be invoked with the messagebox itself.


1 Answers

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`
like image 72
mata Avatar answered Oct 07 '22 21:10

mata