Reputation: 1804
I've got a feeling this will end in a facepalm, but I just can't puzzle out why this import x from y
scenario isn't working for me. As a starting point, take the following module main.py
:
import Tkinter as tk
import tkFont
__metaclass__ = type
#Create widgets
root = tk.Tk()
fntPlainText = tkFont.Font(family='Courier New',size=10)
lblDisplay = tk.Label(root, relief=tk.SUNKEN,
font=fntPlainText,
width=30,height=5,
text='This is a test!')
#Do layout
lblDisplay.grid(padx=5,pady=5)
#Begin app
tk.mainloop()
This runs normally and puts up a small label with the expected content:
So now I want to move the definition of this Font
object to a separate module, so I can share it among multiple applications. My updated code modules are fonts1.py
:
import Tkinter as tk
import tkFont
__metaclass__ = type
fntPlainText = tkFont.Font(family='Courier New',size=10)
...and main1.py
:
import Tkinter as tk
from fonts1 import fntPlainText
__metaclass__ = type
#Create widgets
root = tk.Tk()
lblDisplay = tk.Label(root, relief=tk.SUNKEN,
font=fntPlainText,
width=30,height=5,
text='This is a test!')
#Do layout
lblDisplay.grid(padx=5,pady=5)
#Begin app
tk.mainloop()
But when I run main1.py
, I get a traceback:
Traceback (most recent call last):
File "G:\Python\experiments\investigations\tk\main1.py", line 2, in <module>
from fonts1 import fntPlainText
File "G:\Python\experiments\investigations\tk\fonts1.py", line 5, in <module>
fntPlainText = tkFont.Font(family='Courier New',size=10)
File "C:\Python27\lib\lib-tk\tkFont.py", line 89, in __init__
tk.call("font", "create", self.name, *font)
AttributeError: 'NoneType' object has no attribute 'call'
From Googling and experimenting, I found enough to know that something's going wrong with the assignment of fntPlainText
, but (again) I can't figure out what it is. The biggest puzzle of the whole situation is that when I pare down fonts1.py
to simply define fntPlainText
as a tuple--
Modified fonts1.py
:
fntPlainText = ('Courier New',10)
Running main1.py
now completes normally and paints the same window as main.py
.
If it matters, the environment is Python 2.7.x running on Windows 7.
Upvotes: 1
Views: 2515
Reputation: 359
You need to create a root window (tk.Tk()) before creating the font. If you move your
from fonts1 import fntPlainText
below the tk.Tk() call it should work as you expect.
Upvotes: 2