本文介绍了为什么 tkinter ttk 显示“名称 ttk 未定义"?在 python 3.5.1 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个简单的代码:

from tkinter import *
from tkinter.ttk import *
root= Tk()
ttk.Label(root, text='Heading Here').grid(row=1, column=1)
ttk.Separator(root,orient=HORIZONTAL).grid(row=2, columnspan=5)
root.mainloop()

当我运行此代码时,它显示错误

when i run this code it's showing error

ttk.Label(root, text='Heading Here').grid(row=1, column=1)
NameError: name 'ttk' is not defined

推荐答案

当您执行 import X 时,您正在导入一个名为 X 的模块.从现在开始,X 将被定义.

When you do import X, you are importing a module named X. From this point on, X will be defined.

当你做from X import *时,你不是导入X,你只是导入里面的东西X.X 本身将是未定义的.

When you do from X import *, you are not importing X, you are only importing the things that are inside of X. X itself will be undefined.

因此,当您执行 from tkinter.ttk import * 时,您不是在导入 ttk,您只是在导入 in ttk.这将导入诸如LabelButton 等内容,但不会ttk 本身.

Thus, when you do from tkinter.ttk import *, you are not importing ttk, you are only importing the things in ttk. This will import things such as Label, Button, etc, but not ttk itself.

在python3中导入ttk的正确方法是使用以下语句:

The proper way to import ttk in python3 is with the following statement:

from tkinter import ttk

有了这个,你可以用ttk.Label引用ttk标签,用ttk.Button等引用ttk按钮

With that, you can reference the ttk label with ttk.Label, the ttk button as ttk.Button, etc.

注意:执行 from tkinter.ttk import * 是危险的.不幸的是,ttktkinter 都导出同名的类.如果您同时执行 from tkinter import *from tkinter.ttk import *,您将用另一个类覆盖一个类.导入的顺序将改变您的代码的行为方式.

Note: doing from tkinter.ttk import * is dangerous. Unfortunately, ttk and tkinter both export classes with the same name. If you do both from tkinter import * and from tkinter.ttk import *, you will be overriding one class with another. The order of the imports will change how your code behaves.

出于这个原因——特别是在 tkinter 和 ttk 的情况下,每个类都有几个重叠的类——应该避免通配符导入.PEP8,官方 Python 风格指南,正式禁止通配符导入:

For this reason -- particularly in the case of tkinter and ttk which each have several classes that overlap -- wildcard imports should be avoided. PEP8, the official python style guide, officially discourages wildcard imports:

应避免通配符导入( from import * ),因为它们使命名空间中存在哪些名称变得不清楚,使读者和许多自动化工具都感到困惑.

注意:您的问题暗示您使用的是 python 3,但如果您使用的是 python 2,则可以执行 import ttk 而不是 from tkinter import ttk.ttk 在 python 3 中移动.


Note: your question implies you're using python 3, but in case you're using python 2 you can just do import ttk rather than from tkinter import ttk. ttk moved in python 3.

这篇关于为什么 tkinter ttk 显示“名称 ttk 未定义"?在 python 3.5.1 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 21:43