使用字体模块的 Tkinter 代码无法从命令行运行?

Msg*_*Msg 2 python tkinter python-idle

我有使用 tkinter 的代码,我可以从 IDLE 运行它,但是AttributeError: 'module' object has no attribute 'font'当它从命令行运行时会抛出异常。其他 tkinter 程序工作正常,但任何使用 tkinter 包的 font.py 的东西都会给我这个错误。

我检查了我的 python 文件,并且 c:/Python34/Lib/tkinter/font.py 就在那里。我不知道为什么,从命令行,它认为字体是一个属性,而不是 tkinter 包的模块。

示例代码:

import tkinter as tk
from tkinter import ttk

root = tk.Tk()

test_font = tk.font.Font(size=12,weight='bold')

root.mainloop()
Run Code Online (Sandbox Code Playgroud)

dee*_*ets 7

同样在这里:

 Type "help", "copyright", "credits" or "license" for more information.
 >>> import tkinter as tk
 >>> tk.font
 AttributeError: 'module' object has no attribute 'font'
Run Code Online (Sandbox Code Playgroud)

答案很简单:Python 不会自动导入所有模块层次结构,仅仅因为您导入了顶级层次结构。那些这样做的人(例如os,将os.path提供)必须明确地为此编写代码。

但是,由于 IDLE 使用tkinter自身,它已经导入了tkinter.font,因此您认为没有该导入就可以逃脱。你不能。只需添加import tkinter.font,它就可以工作。