有一种比使用.config()更改应用程序字体更好的方法,特别是当您的目标是更改整个小部件组(或所有小部件)的字体时。
Tk真正伟大的特性之一是“命名字体”的概念。命名字体的优点是,如果您更新字体,所有使用该字体的小部件都将自动更新。因此,只需将小部件配置为使用这些自定义字体,然后更改属性就很简单了。
下面是一个简单的例子:try:
import Tkinter as tk
import tkFont
# import ttk # not used here
except ImportError: # Python 3
import tkinter as tk
import tkinter.font as tkFont
# import tkinter.ttk as ttk # not used here
class App:
def __init__(self):
root=tk.Tk()
# create a custom font
self.customFont = tkFont.Font(family="Helvetica", size=12)
# create a couple widgets that use that font
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()
text.pack()
text.insert("end","press +/- buttons to change\nfont size")
# create buttons to adjust the font
bigger = tk.Button(root, text="+", command=self.OnBigger)
smaller = tk.Button(root, text="-", command=self.OnSmaller)
bigger.pack(in_=buttonframe, side="left")
smaller.pack(in_=buttonframe, side="left")
root.mainloop()
def OnBigger(self):
'''Make the font 2 points bigger'''
size = self.customFont['size']
self.customFont.configure(size=size+2)
def OnSmaller(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 tkFont
root = tk.Tk()
label = tk.Label(root, text="Hello, world")
font = tkFont.Font(font=label['font'])
print font.actual()
当我运行上面的程序时,我得到以下输出:{'family': 'Lucida Grande',
'weight': 'normal',
'slant': 'roman',
'overstrike': False,
'underline': False,
'size': 13}