python 3 tkinter Pycharm - 消息框错误

python 3 tkinter Pycharm - error on messagebox

我正在写一个 GUI,我说:

from tkinter import *

程序中还有一个函数是:

def nameFunc():
    messagebox.showinfo(........)

问题是,通过 运行 最新 Pycharm 中的代码,它告诉我消息框未定义,即使我已经从 tkinter 导入了所有内容,它只有在我明确地导入时才有效说:

from tkinter import messagebox

这仅在我 运行 Pycharm 上的代码时发生,在标准 python IDLE 中它很好。

为什么?

PyCharm 的行为完全正常,如果您查看 documentation on packages:

what happens when the user writes from sound.effects import *? Ideally, one would hope that this somehow goes out to the filesystem, finds which submodules are present in the package, and imports them all. This could take a long time and importing sub-modules might have unwanted side-effects that should only happen when the sub-module is explicitly imported.

The only solution is for the package author to provide an explicit index of the package. The import statement uses the following convention: if a package’s __init__.py code defines a list named __all__, it is taken to be the list of module names that should be imported when from package import * is encountered.

tkinter 没有定义 __all__ 来自动导入子模块,你应该庆幸它不会自动导入它们:

import tkinter.__main__

print("this will only print after you close the test window")

程序仅在 window 弹出当前 tcl/Tk 版本并且关闭其他一些内容后才继续 运行,要导入必须显式导入的包的子模块他们:

from tkinter import messagebox

然而,正如我在 中所描述的,由于 IDLE 的构建方式,当您的代码在空闲状态下执行时,它已经加载了一些子模块 Shell.