在Python中导入Tkinter时出现ImportError
我正在尝试使用 Python 3.2 和标准库 Tkinter 测试 GUI 代码,但无法导入该库。
这是我的测试代码:
from Tkinter import *
root = Tk()
w = Label(root, text="Hello, world!")
w.pack()
root.mainloop()
shell 报告此错误:
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
from Tkinter import *
ImportError: No module named Tkinter
I'm trying to test GUI code using Python 3.2 with standard library Tkinter but I can't import the library.
This is my test code:
from Tkinter import *
root = Tk()
w = Label(root, text="Hello, world!")
w.pack()
root.mainloop()
The shell reports this error:
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
from Tkinter import *
ImportError: No module named Tkinter
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
问题的根源在于,Tkinter 模块在 python 2.x 中名为
Tkinter
(大写“T”),在 python 3 中名为tkinter
(小写“t”) .x。要使您的代码在 Python 2 和 3 中工作,您可以执行以下操作:
但是,PEP8 关于通配符导入有这样的说法:
尽管有无数教程忽略 PEP8,但符合 PEP8 的导入方式将如下所示:
以这种方式导入时,您需要在所有 tkinter 命令前添加前缀
tk.
(例如:root = tk.Tk()
等)。这将使您的代码更容易理解,但需要稍微多输入一些内容。鉴于 tkinter 和 ttk 经常一起使用并导入同名的类,这是一件好事。正如Python之禅所说:“显式优于隐式”。注意:
as tk
部分是可选的,但可以让您少输入一些内容:tk.Button(...)
与tkinter.Button(.. .)
The root of the problem is that the Tkinter module is named
Tkinter
(capital "T") in python 2.x, andtkinter
(lowercase "t") in python 3.x.To make your code work in both Python 2 and 3 you can do something like this:
However, PEP8 has this to say about wildcard imports:
In spite of countless tutorials that ignore PEP8, the PEP8-compliant way to import would be something like this:
When importing in this way, you need to prefix all tkinter commands with
tk.
(eg:root = tk.Tk()
, etc). This will make your code easier to understand at the expense of a tiny bit more typing. Given that both tkinter and ttk are often used together and import classes with the same name, this is a Good Thing. As the Zen of python states: "explicit is better than implicit".Note: The
as tk
part is optional, but lets you do a little less typing:tk.Button(...)
vstkinter.Button(...)
在 3.x 中,该模块称为
tkinter
,而不是Tkinter
。The module is called
tkinter
, notTkinter
, in 3.x.对于 3.x,使用
Tkinter
将代码重写为tkinter
(小写):Rewrite the code as follows with
Tkinter
astkinter
(lowercase) for 3.x: