1

我正在为我的第一个 tkinter 应用程序重写代码,我在其中避免使用类。那是一条死胡同,我最终不得不学习 Python 中的类编程。我遇到了一个非常奇怪的错误,我不知道如何解决它。我试过了,但没有效果。我想要做的是在我的应用程序中为两个标签指定字体。它在我以前的无类代码中运行良好,但现在它给了我一个错误:

(...) line 56, in create_widgets
TimeFont = font.Font(family='Palatino', size=88, weight='bold')
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/tkinter/font.py", line 71, in __init__
root = tkinter._default_root
AttributeError: 'module' object has no attribute '_default_root'

这是我用于创建小部件的功能:

def create_widgets(self):
    self.set_timer = ttk.Entry(self, textvariable=self.timer)
    self.start = ttk.Button(self, text='Start', command=self.start)
    TimeFont = font.Font(family='Palatino', size=88, weight='bold') #the infamous line 56
    self.display1 = ttk.Label(self, textvariable=self.player1, font=TimeFont)
    self.display2 = ttk.Label(self, textvariable=self.player2, font=TimeFont)

如果相关,还有一些“来自上面”的代码:

from decimal import *
from tkinter import *
from tkinter import ttk
from tkinter import font
import time, _thread, subprocess

class Chclock(ttk.Frame):

    @classmethod
    def main(cls):
        NoDefaultRoot()
        root = Tk()
        app = cls(root)
        app.grid(sticky=NSEW)
        root.grid_columnconfigure(0, weight=1)
        root.grid_rowconfigure(0, weight=1)
        root.resizable(True, False)
        root.mainloop()

    def __init__(self, root):
        super().__init__(root)
        root.bind('q', self.player1move)
        root.bind('p', self.player2move)
        root.bind('b', self.pause)
        root.bind('a', self.undo)
        root.bind('l', self.undo)
        self.create_variables()
        self.create_widgets() #here I call the function containing the error
        self.grid_widgets()
        self.grid_columnconfigure(0, weight=1)

这可能很愚蠢,但我就是不明白是什么导致了这个问题。它曾经工作得很好...

谢谢!

4

2 回答 2

1

也许代码“NoDefaultRoot()”和错误消息“对象没有属性'_default_root'”可能彼此有关?注意到相关性了吗?调试的第一条规则是假设错误消息告诉你一些有用的东西。

问题是您正在创建一个字体对象而没有告诉该对象它属于哪个窗口。由于您没有告诉它,它选择使用默认的根窗口。但是,您明确要求没有默认根窗口。

这是构建 Tkinter 程序的一种有点奇怪的方式。我建议阅读Python Tkinter Program Structure问题中的答案

于 2013-07-13T21:34:46.847 回答
0

好吧,我已经设法找到了。由于某个好心人给了这个问题一个赞成票,我将发布解决方案:我已删除该NoDefaultRoot()行。我不确定为什么它不起作用,为什么它现在起作用,但它确实......有人可以解释评论中发生了什么吗?我对这些东西真的很陌生,我删除的那行带有一个模板。

对不起,如果我弄得一团糟。

于 2013-07-13T17:30:58.667 回答