python-3.x - 为什么先导入 * 然后 ttk?

标签 python-3.x tkinter tk

我的理解是 tkinter 程序的标准设置是这样开始的:

from tkinter import *
from tkinter import ttk

我知道 tkinter 是一个包,但如果我已经用 * 导入了所有内容,为什么我还需要导入ttk ?为什么我取出第二行并尝试引用ttk会报错?

最佳答案

当您这样做时from some_package import * , python 将导入该包选择导出的任何内容。它选择导出的内容可能是实际存储在包文件夹中的内容的子集。为什么?没有特别的原因,这只是包作者决定做事的方式。

有关导出内容的信息在 __init__.py 中定义。包内的文件(在本例中为 tkinter/init.py )。如果您查看该文件,您会注意到它本身不会导入 ttk,因此 ttk 不会被导出,因此无法通过通配符导入来导入。

同样,除了 tkinter 和 ttk 的作者选择做事的方式之外,没有什么特别的原因。

有关打包机制的更多信息,请参阅 python 教程的打包部分 ( https://docs.python.org/3/tutorial/modules.html#packages )

导入 tkinter 的更好方法

您可能认为这是标准的,因为许多教程都是这样做的,但这通常是一种不好的做法。 IMO 更好的方法是给 tkinter 库一个明确的名称:

# python 3.x
import tkinter as tk
from tkinter import ttk 

# python 2.x
import Tkinter as tk
import ttk

这将使您的代码更易于阅读,因为您必须明确说明您正在使用哪个工具包:
b1 = tk.Button(...) # uses a standard tk button
b2 = ttk.Button(...) # uses a ttk button

我想不出任何其他方式来做这件事的充分理由。每次调用 tkinter 函数时,进行全局导入会为您节省几个字节,但会牺牲清晰度。此外,它强化了一种不良做法,可能会影响您使用其他库的方式。

IMO 的真正权威是 PEP8 ,这对此事有以下说法:

Wildcard imports (from import *) should be avoided as they make it unclear which names are present in the namespace, confusing both readers and many automated tools. There is one defensible use case for a wildcard import, which is to republish an internal interface as part of a public API (for example, overwriting a pure Python implementation of an interface with the definitions from an optional accelerator module and exactly which definitions will be overwritten isn't known in advance).

关于python-3.x - 为什么先导入 * 然后 ttk?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24725920/

相关文章:

Python TKInter : AttributeError: 'NoneType' object has no attribute 'create_image'

python - 如何使用 Python Tkinter 使按钮打开特定的 .csv 文件?

tcl - 创建并使用新的 ttk::notebook 选项卡样式

python-3.x - 将字典嵌套在另一个字典中,按 Pandas Dataframe 中的值进行分组

python - 无法以正确的格式将数据提取到 Pandas 数据框中

python - 圆的周长上有点的三角形,python

perl - Perl Tk 模块的缺点是什么?

python - Pandas 内爆数据框,其值由字符分隔

python - 使用python shelve跨平台

python-3.x - Python Tkinter GUI 与 PyQT 的内存节省