Tkinter code using font module can't run from

2019-08-05 14:06发布

I have code using tkinter which I can run from IDLE just fine, but which throws the exception AttributeError: 'module' object has no attribute 'font' when it is run from the command line. Other tkinter programs work fine, but anything using the tkinter package's font.py gives me this error.

I've checked my python files and c:/Python34/Lib/tkinter/font.py is there. I am not sure why, from the command line, it thinks font is an attribute and not a module of the tkinter package.

Example code:

import tkinter as tk
from tkinter import ttk

root = tk.Tk()

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

root.mainloop()

1条回答
闹够了就滚
2楼-- · 2019-08-05 14:47

Same here:

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

The answer is simple: Python doesn't automagically import all module hierarchies, just because you import the top-level one. Those who do (e.g. os, which will make os.path available) have to explicitly write code for that.

However, as IDLE uses tkinter itself, it has already imported tkinter.font, thus you think you can get away without that import. You can't. Just add import tkinter.font, and it works.

查看更多
登录 后发表回答