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

1

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()
Grimona answered 16/6, 2015 at 20:4 Comment(2)
This Q and A inspired bugs.python.org/issue25507. In IDLE for 3.5.3 and 3.6.a4, "import tkinter; tkinter.font' will raise AttributeError.Cufic
My answer here: #38807173 describes how to patch IDLE in existing releases to give the proper error message.Cufic
K
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.

Katelin answered 16/6, 2015 at 20:12 Comment(1)
Perfect, thank you very much! I didn't even think about the fact that IDLE would use tkinter. Very good to know. Thanks again!Grimona

© 2022 - 2024 — McMap. All rights reserved.