Python tk 消息框导入混淆

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16374775/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:25:26  来源:igfitidea点击:

tk messagebox import confusion

pythonpython-3.xtkinterimport

提问by Apple

I'm just beginning to learn tkinter at the moment, and when importing messagebox I found that I must not really understand import statements.

我现在才刚刚开始学习 tkinter,在导入 messagebox 时,我发现我一定不能真正理解导入语句。

The thing that confuses me is that:

让我困惑的是:

import tkinter as tk

def text_box():
    if tk.messagebox.askokcancel("Quit", "Never Mind"):
        root.destroy()

root = tk.Tk()
button = tk.Button(root, text="Press the button", command=text_box)
button.pack()
root.mainloop()

compiles fine, but pressing the button gives the error 'module' object has no attribute 'messagebox', while the code:

编译正常,但按下按钮会出现错误'module' object has no attribute 'messagebox',而代码:

import tkinter as tk
from tkinter import messagebox

...
    if messagebox.askokcancel("Quit", "Never Mind"):
...

...works without a hitch.

...工作顺利。

I get a similar error if I import with from tkinter import *.

如果我使用from tkinter import *.

The help for tkinter shows messageboxin the list of PACKAGE CONTENTS, but I just can't load it in the normal way.

tkinter 的帮助显示messagebox在 的列表中PACKAGE CONTENTS,但我无法以正常方式加载它。

So my question is, why...and what is it about importing that I don't understand?

所以我的问题是,为什么......以及我不明白的导入是什么?

Just thought I should mention—the code only works in Python 3, and in Python 2.x messageboxis called tkMessageBoxand is not defined in tkinter.

只是想我应该提到 - 该代码仅在 Python 3 中有效,而在 Python 2.x 中messagebox被调用tkMessageBox且未在tkinter.

采纳答案by mata

tkinter.messageboxis a module, not a class.

tkinter.messagebox是一个模块,而不是一个类。

As it isn't imported in tkinter.__init__.py, you explicitly have to import it before you can use it.

由于它未导入tkinter.__init__.py,因此您必须明确导入它才能使用它。

import tkinter
tkinter.messagebox  # would raise an ImportError
from tkinter import messagebox
tkinter.messagebox  # now it's available eiter as `messagebox` or `tkinter.messagebox`

回答by Targo_viste

try this

尝试这个

import sys

from tkinter import *

... and your code

...和你的代码