5

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()
2

1 Answer 1

15

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect, thank you very much! I didn't even think about the fact that IDLE would use tkinter. Very good to know. Thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.