You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Tkinter Text组件中特定词语/短语修改字体?

在Tkinter Text组件中为指定文本应用自定义字体

要实现给不同词语/句子设置不同字体,核心是利用Tkinter Text组件的**标签(Tag)**功能,通过tag_config()定义字体样式,tag_add()将样式绑定到指定文本范围即可。以下是针对你代码的具体修改方案:

关键修改步骤

  1. 移除apply_font_to_text方法中重复创建FontExtractor的冗余代码,直接遍历传入的font_word_tuple处理每个词语。
  2. 清空目标Text组件内容,逐个插入词语并为每个词语绑定对应字体的标签。
  3. 配置标签的字体样式,将标签应用到刚插入的文本范围。

修改后的完整代码

from wordToneRecog.font_apply import *
import tkinter
from PIL import Image, ImageTk

# 自定义字体映射(确保这些字体已安装在系统中)
available_fonts = {
    "superior": "Black Ops One", 
    "old": "Dancing Script", 
    "mystery": "Sedgwick Ave Display", 
    "new": "Ethnocentric Rg", 
    "lively": "Pricedown Bl"
}

# 创建GUI窗口
root = tkinter.Tk()
root.title("Text Mood Font Changer")
root.state('zoomed')
win_width, win_height = (root.winfo_width(), root.winfo_height())

def copy_button(OutText: str):
    root.clipboard_clear()
    root.clipboard_append(OutText)
    root.update()

# 加载复制按钮图片
im = Image.open('pathto\\copy.png')
im = im.resize((30, 30))
ph = ImageTk.PhotoImage(im)

class FontFormater():
    def __init__(self):
        self.corresponding_font = []
    
    def format_font(self, font_word_tuple):
        for each_tuple in font_word_tuple:
            self.corresponding_font.append((each_tuple[0], available_fonts[each_tuple[1]]))
        return self.corresponding_font
    
    def apply_font_to_text(self, widgetVar, font_word_tuple):
        widgetVar.configure(state='normal')
        # 清空原有内容
        widgetVar.delete("1.0", tkinter.END)
        
        for each_tuple in font_word_tuple:
            word = each_tuple[0]
            tone = each_tuple[1]
            desired_font = available_fonts[tone]
            
            # 生成唯一标签名(避免重复)
            tag_name = f"font_{tone}"
            
            # 配置标签的字体样式(字号可根据需求调整)
            widgetVar.tag_config(tag_name, font=(desired_font, 20))
            
            # 获取当前插入位置
            current_pos = widgetVar.index(tkinter.END)
            # 插入词语(加空格分隔,可根据文本格式调整)
            widgetVar.insert(current_pos, f"{word} ")
            # 获取插入后的位置
            new_pos = widgetVar.index(tkinter.END)
            
            # 将标签应用到刚插入的文本范围
            widgetVar.tag_add(tag_name, current_pos, new_pos)
        
        # 设置组件为不可编辑状态
        widgetVar.configure(state='disabled')

# 创建文本组件
input_text = tkinter.Text(root, height=19, width=38, font=('Arial', 20))
output_text = tkinter.Text(root, height=16, width=35)
copy_output_button = tkinter.Button(root, image=ph, command=lambda: copy_button(output_text.get("1.0", 'end-1c')))

# 提取词语与语气的对应关系
ff_extractor = FontExtractor("In London's heart, a tale unfolds,\n A city of stories, legends of old.")
font_word_tuple = ff_extractor.extract_font()

# 应用字体到输出组件
FontFormater().apply_font_to_text(output_text, font_word_tuple)

# 布局组件
input_text.place(x=40, y=60)
output_text.place(x=(((win_width*1000)/20)*13), y=60)
copy_output_button.place(x=1280, y=20)

root.mainloop()

代码解释

  • 标签配置:tag_config(tag_name, font=(desired_font, 20))定义了标签对应的字体和字号,相同语气的词语会复用同一个标签,避免重复配置。
  • 文本插入与标签绑定:每次插入词语前记录当前位置,插入后获取新位置,用tag_add()将标签绑定到这个位置区间,确保该词语应用指定字体。
  • 组件状态控制:操作文本前设置state='normal'允许编辑,完成后设置state='disabled'防止用户修改。

内容的提问来源于stack exchange,提问作者Ethan Rodrigues

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 20:40:56