简体   繁体   English

Python tkinter 8.5 导入消息框

[英]Python tkinter 8.5 import messagebox

The following code runs fine within IDLE, but otherwise I get "NameError: global name 'messagebox' is not defined".以下代码在 IDLE 中运行良好,但否则我会收到“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 messagebox ,它可以从任何地方正常运行。

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?为什么 IDLE 不需要显式导入语句,但在其他地方却需要?

the messagebox is a separate submodule of tkinter, so simply doing a complete import from tkinter:消息框是 tkinter 的一个单独的子模块,因此只需从 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与必须显式导入 ttk 的方式相同

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它在 idle 中工作的原因是因为 idle 出于自己的目的导入了 messagebox,并且由于 idle 的工作方式,在 idle 工作时可以访问它的导入

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. IDLE 是用 Python 编写的,GUI 使用 Tkinter,因此看起来您的程序正在使用 IDLE 本身正在使用的import语句。 However, you should explicitly include the import statement for the messagebox if you want to execute your program outside the IDLE process.但是,如果您想在 IDLE 进程之外执行您的程序,您应该明确地包含messageboximport语句。

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. messagebox.showinfotkinter/showinfo.py定义,但是当您使用from tkinter import * tkinter/showinfo.py from tkinter import *您只导入tkinter/__init__.py ,其中包含LabelEntryButton的定义……这就是 python 导入的工作方式。

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当您使用from tkinter import messagebox它会在tkinter/__init__.py查找messagebox但找不到它,因此它尝试导入tkinter/messagebox.py

As for the IDLE anomaly, it is a bug in IDLE and I believe that it was patched.至于 IDLE 异常,这是 IDLE 中的一个错误,我相信它已被修补。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM