如果你的目标是改变一组或所有小部件的字体,那么使用.config()
来改变应用程序字体的方法不如使用更好的方法。
Tk中一个非常棒的功能是“命名字体”,它们在tkinter中作为对象实现。命名字体的优点在于,如果你更新了字体,使用该字体的所有小部件都会自动更新。因此,将小部件配置为使用字体对象后,只需更改字体对象的配置,即可一次性更新所有小部件。
以下是一个快速示例:
import tkinter as tk
import tkinter.font
class App:
def __init__(self):
root=tk.Tk()
self.customFont = tkinter.font.Font(family="Helvetica", size=12)
buttonframe = tk.Frame()
label = tk.Label(root, text="Hello, world", font=self.customFont)
text = tk.Text(root, width=20, height=2, font=self.customFont)
buttonframe.pack(side="top", fill="x")
label.pack(side="top", fill="x")
text.pack(side="top", fill="both", expand=True)
text.insert("end","press +/- buttons to change\nfont size")
increase_font = tk.Button(root, text="+", command=self.increase_font)
decrease_font = tk.Button(root, text="-", command=self.decrease_font)
increase_font.pack(in_=buttonframe, side="left")
decrease_font.pack(in_=buttonframe, side="left")
root.mainloop()
def increase_font(self):
'''Make the font 2 points bigger'''
size = self.customFont['size']
self.customFont.configure(size=size+2)
def decrease_font(self):
'''Make the font 2 points smaller'''
size = self.customFont['size']
self.customFont.configure(size=size-2)
app=App()
如果您不喜欢这种方法,或者想要基于默认字体创建自定义字体,或者只是更改一个或两个字体以表示状态,您可以使用font.actual
来获取给定小部件字体的实际大小。例如:
import tkinter as tk
import tkinter.font
root = tk.Tk()
label = tk.Label(root, text="Hello, world")
font = tkinter.font.Font(font=label['font'])
print(font.actual())
运行以上代码后,我得到以下输出:
{'family': 'Lucida Grande',
'weight': 'normal',
'slant': 'roman',
'overstrike': False,
'underline': False,
'size': 13}