2013-10-22 20 views
3

當我運行這段代碼:AttributeError的時候試圖用tkFont

from Tkinter import * 
import tkFont 

class Statify(): 

    def __init__(self): 

     ### Broken 
     self.titleFont = tkFont.Font(family='Helvetica', size=24, weight='bold') 
     self.option_add(*Label*font, self.titleFont) 
     ### 

     self.root = Tk() 
     self.root.withdraw() 
     self.main = Toplevel(self.root) 
     self.main.title('') 
     self.main_header = Frame(self.main) 
     self.main_footer = Frame(self.main) 
     self.main_title = Label(self.main_header, text='Statify Me v1.0 (WIP)') 
     self.main_exit = Button(self.main_footer, text='Quit', command=quit) 
     self.main_header.pack() 
     self.main_footer.pack() 
     self.main_title.pack() 
     self.main_exit.pack() 
     mainloop() 

statify = Statify() 

我得到:

Traceback (most recent call last): 
    File "Statify.py", line 23, in <module> 
    statify = Statify() 
    File "Statify.py", line 7, in __init__ 
    self.titleFont = tkFont.Font(family='Helvetica', size=24, weight='bold') 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/tkFont.py", line 88, in __init__ 
AttributeError: 'NoneType' object has no attribute 'tk' 

從我讀過的東西,這應該工作,以及使用選項文件而不是沒有按沒有什麼不同。

Python版本2.7.2 Tkinter的優化版本8.5

+0

這是整個代碼? – karthikr

+0

我很快解釋了一個更大的應用程序的破碎部分,並因此引入了一些語法錯誤(其中一些是您編輯的 - 歡呼!)。 Brionius的回答爲我工作。謝謝! – insiduoustek

回答

5

如果你看一下docs for tkFont,你會看到的問題是,tkFont.Font需要一個root論點 - 即父控件。通過呼叫轉移到tkFont.Font在其中創建根窗口下方解決這個問題,再加入self.root作爲關鍵字參數,就像這樣:

self.root = Tk() 
self.titleFont = tkFont.Font(root=self.root, family='Helvetica', size=24, weight='bold') 
          ^^^^^^^^^^^^^^ 

你沒有得到這個錯誤還,但有問題與下一行 - 我認爲你的意思是寫self.root.option_add而不是self.option_add,我不知道你想要做什麼*Label*font業務。

+0

謝謝你解釋這個問題,並解決我接下來會注意到的問題。我試圖指定字體樣式用於特定類型的所有小部件 - 在此代碼中使用Label作爲示例。但我打算使用選項文件爲整個應用程序執行此操作。謝謝你的幫助! – insiduoustek

相關問題