简体   繁体   English

导入 tkinter 的“messagebox”模块时,“import tkinter.messagebox”语法是否不起作用?

[英]When importing tkinter's “messagebox” module, does the “import tkinter.messagebox” syntax not work?

Since the "messagebox" is a module in the "tkinter" package, why do I have to use既然“messagebox”是“tkinter”包中的一个模块,那我为什么要使用

from tkinter import messagebox

instead of代替

import tkinter.messagebox

I was under the impression that to import a module within a package I would have to use the following syntax:我的印象是要在包中导入模块,我必须使用以下语法:

import package_name.module_name 

Thanks for your help.谢谢你的帮助。

Importing tkinter.messagebox does work (at least in should, and does in 3.4, maybe there might be a bug in other releases) , but it is imported as tkinter.messagebox , which is tedious and lengthy to write, and if the rest of tkinter is being used, it is pointless to do, seeing as tkinter.messagebox will have already been indirectly imported.导入 tkinter.messagebox 确实有效(至少在 should 和 3.4 中确实如此,也许其他版本中可能存在错误) ,但它被导入为tkinter.messagebox ,编写起来既乏味又冗长,如果其余的tkinter正在被使用,这样做是没有意义的,因为tkinter.messagebox已经被间接导入了。 So generally from tkinter import messagebox is considered easier, and does not loose much, if any readability.所以通常from tkinter import messagebox被认为更容易,并且不会丢失太多,如果有任何可读性的话。

messagebox, along with some other modules like filedialog, does not automatically get imported when you import tkinter.导入 tkinter 时,messagebox 以及其他一些模块(如 filedialog)不会自动导入。 Import it explicitly, using as and/or from as desired.根据需要使用 as 和/或 from 显式导入它。 check below 3 examples for better clarification-检查以下 3 个示例以获得更好的说明-

    >>> import tkinter
    >>> tkinter.messagebox.showinfo(message='hi')

Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute 'messagebox'

. .

    >>> import tkinter.messagebox
    >>> tkinter.messagebox.showinfo(message='hi')

'ok'

. .

 >>> from tkinter import messagebox
    >>> messagebox.showinfo(message='hi')

'ok'

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

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