Python tkinter 8.5 import messagebox

一世执手 提交于 2019-12-18 07:12:10

问题


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?


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/24738104/python-tkinter-8-5-import-messagebox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!