Big Sharpie
Big Sharpie

Reputation: 849

Python tkinter 8.5 import messagebox

The following code runs fine within IDLE, but otherwise I get "NameError: global name 'messagebox' is not defined". However, if I explicitly state from tkinter import messagebox, it runs fine from where ever.

from tkinter import *
from tkinter import ttk 

root = Tk()
mainFrame = ttk.Frame(root)
messagebox.showinfo("My title", "My message", icon="warning", parent=mainFrame)

Why does IDLE not need the explicit import statement but elsewhere it is required?

Upvotes: 2

Views: 4970

Answers (3)

TheLizzard
TheLizzard

Reputation: 7680

messagebox.showinfo is defined inside tkinter/showinfo.py but when you use from tkinter import * you only import tkinter/__init__.py which holds the definitions of Label, Entry, Button, ... That is how python imports work.

When you use from tkinter import messagebox it looks for messagebox inside tkinter/__init__.py but it can't find it so it tries to import tkinter/messagebox.py

As for the IDLE anomaly, it is a bug in IDLE and I believe that it was patched.

Upvotes: 1

James Kent
James Kent

Reputation: 5933

the messagebox is a separate submodule of tkinter, so simply doing a complete import from tkinter:

from tkinter import *

doesn't import messagebox

it has to be explicitly imported like so:

from tkinter import messagebox

in the same way that ttk has to be imported explicitly

the reason it works in idle is because idle imports messagebox for its own purposes, and because of the way idle works, its imports are accessible while working in idle

Upvotes: 10

A. Rodas
A. Rodas

Reputation: 20679

IDLE is written in Python and uses Tkinter for the GUI, so it looks like your program is using the import statements that IDLE itself is using. However, you should explicitly include the import statement for the messagebox if you want to execute your program outside the IDLE process.

Upvotes: 5

Related Questions