python - 在 tkinter 中设置字体返回错误

标签 python tkinter tk-toolkit

我正在重写我的第一个 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)

这可能是一些愚蠢的事情,但我就是无法理解是什么导致了这个问题。它曾经工作得很好...

谢谢!

最佳答案

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

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

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

关于python - 在 tkinter 中设置字体返回错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17632080/

相关文章:

python - 如何使用 Postgres 在 Django 中的 JSONField 中搜索带空格的键?

python - 如何以编程方式区分普通网址和图片网址

python - 有没有办法以编程方式生成 Python 字节码?

python - 如何在按下按钮时查看菜单?

python - 如何从 tkinter 中的单选按钮获取值?

bind - 如何绑定(bind) '+'和 '-'键是Tcl/Tk

python - 类级装饰器

python - Tkinter 按钮不运行命令

python - 进度条显示已播放的音乐量

python - 如何将多个鼠标按钮绑定(bind)到一个小部件?