Python tkinter 8.5 导入消息框

问题描述:

以下代码在 IDLE 中运行良好,但否则我会收到NameError: global name 'messagebox' is not defined".但是,如果我明确声明 from tkinter 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)

为什么 IDLE 不需要显式导入语句,而在其他地方却需要?

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

messagebox 是 tkinter 的一个单独的子模块,所以只需从 tkinter 做一个完整的导入:

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

from tkinter import *

不导入消息框

它必须像这样显式导入:

it has to be explicitly imported like so:

from tkinter import messagebox

与必须显式导入 ttk 的方式相同

in the same way that ttk has to be imported explicitly

它在 idle 中工作的原因是因为 idle 为自己的目的导入了 messagebox,并且由于 idle 的工作方式,在 idle 工作时可以访问它的导入

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