【问题标题】:Tkinter code using font module can't run from command line?使用字体模块的 Tkinter 代码无法从命令行运行?
【发布时间】:2026-01-24 00:45:02
【问题描述】:

我有使用 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()

【问题讨论】:

  • 这个问答启发了bugs.python.org/issue25507。在 3.5.3 和 3.6.a4 的 IDLE 中,"import tkinter; tkinter.font' 将引发 AttributeError。
  • 我在这里的回答:*.com/questions/38806673/… 描述了如何在现有版本中修补 IDLE 以提供正确的错误消息。

标签: python tkinter python-idle


【解决方案1】:

这里也一样:

 Type "help", "copyright", "credits" or "license" for more information.
 >>> import tkinter as tk
 >>> tk.font
 AttributeError: 'module' object has no attribute 'font'

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

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

【讨论】:

  • 完美,非常感谢!我什至没有想到 IDLE 会使用 tkinter。很高兴知道。再次感谢!