Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AttributeError when trying to use tkFont

When I run this code:

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()

I get:

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'

From what I've read, this should work, and using an option file instead doesn't make a difference.

Python version 2.7.2 Tkinter verion 8.5

like image 640
insiduoustek Avatar asked Oct 22 '13 15:10

insiduoustek


1 Answers

If you look at the docs for tkFont, you'll see that the problem is that tkFont.Font requires a root argument - i.e. a parent widget. Fix this by moving the call to tkFont.Font below where you create the root window, then add self.root as a keyword argument, like so:

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

You haven't gotten to this bug yet, but there are problems with the next line - I think you meant to write self.root.option_add rather than self.option_add, and I don't know what you're trying to do with the *Label*font business.

like image 126
Brionius Avatar answered Sep 28 '22 07:09

Brionius