5

当我运行此代码时:

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

4

1 回答 1

7

如果您查看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业务做什么。

于 2013-10-22T15:07:37.690 回答