如何在不知道小部件的字体家族/大小的情况下更改其字体样式?

59 投票
8 回答
98556 浏览
提问于 2025-04-16 06:24

有没有办法在不知道Tkinter控件的字体类型和大小的情况下,改变它的字体样式呢?

使用场景:我们用标准的Tkinter控件(比如LabelEntryText等)来创建用户界面。在应用程序运行时,我们可能想动态地把这些控件的字体样式改成粗体或斜体,这时候可以用.config()方法来实现。不过,遗憾的是,似乎没有办法在不指定字体类型和大小的情况下,单独设置字体样式。

以下是我们想要实现的例子,但这两个例子都无法正常工作:

widget.config(font='bold')

或者

widget.config(font=( None, None, 'bold' ))

8 个回答

7

如果你在使用一个有名字的字体,你可以用几条语句来实现你想要的效果:

import tkFont
wfont = tkFont.nametofont(widget['font'])
wfont.config(weight='bold')

已编辑,加入了B. Oakley的评论。

37

如果只需要一个标签的话,可以更简洁一些:

from Tkinter import *
import Tkinter as tk
root = tk.Tk()

# font="-weight bold" does your thing
example = Label(root, text="This is a bold example.", font="-weight bold")
example.pack()

root.mainloop()
68

有一种比使用 .config() 更好的方法来改变你的应用程序字体,特别是当你想要为一组小部件或所有小部件更改字体时。

Tk 的一个很棒的功能是“命名字体”,这些字体在 tkinter 中被实现为对象。命名字体的好处在于,如果你更新了字体,所有使用该字体的小部件都会自动更新。所以,你只需要一次配置你的所有小部件使用一个字体对象,然后只需更改字体对象的配置,就可以一次性更新所有小部件。

这里有个简单的例子:

import tkinter as tk
import tkinter.font


class App:
    def __init__(self):
        root=tk.Tk()
        # create a custom font
        self.customFont = tkinter.font.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(side="top", fill="x")
        text.pack(side="top", fill="both", expand=True)
        text.insert("end","press +/- buttons to change\nfont size")

        # create buttons to adjust the font
        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}

撰写回答