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