尝试使用tkFont时的AttributeError

ins*_*tek 4 python fonts tk-toolkit tkinter attributeerror

当我运行此代码时:

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()
Run Code Online (Sandbox Code Playgroud)

我明白了:

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'
Run Code Online (Sandbox Code Playgroud)

从我所读到的,这应该工作,并使用选项文件而不是有所作为.

Python版本2.7.2 Tkinter版本8.5

Bri*_*ius 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')
                             ^^^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)

你还没有得到这个bug,但是下一行还有问题 - 我认为你的意思是写self.root.option_add而不是self.option_add,而且我不知道你在尝试做什么*Label*font.