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

栏目: Python · 发布时间: 6年前

内容简介:翻译自:https://stackoverflow.com/questions/24725920/why-import-and-then-ttk

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

from tkinter import *
from tkinter import ttk

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

当您从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 isnt known in advance).

翻译自:https://stackoverflow.com/questions/24725920/why-import-and-then-ttk


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Blog Design Solutions

Blog Design Solutions

Richard Rutter、Andy Budd、Simon Collison、Chris J Davis、Michael Heilemann、Phil Sherry、David Powers、John Oxton / friendsofED / 2006-2-16 / USD 39.99

Blogging has moved rapidly from being a craze to become a core feature of the Internetfrom individuals sharing their thoughts with the world via online diaries, through fans talking about their favori......一起来看看 《Blog Design Solutions》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

URL 编码/解码
URL 编码/解码

URL 编码/解码

MD5 加密
MD5 加密

MD5 加密工具