Tkinter code using font module can't run from command line?

Question:

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()
Asked By: Msg

||

Answers:

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 automatically import all module hierarchies, just because you import the top-level one. Packages that 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.

Answered By: deets
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.