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

Python Tkinter实现输入时动态修改Label指定字符字体颜色

解决动态修改打字测试字符颜色的问题

你遇到的核心问题是单个Label组件无法拆分字符样式——Label的文本是整体渲染的,没法单独给某个字符设置颜色。要实现目标效果,推荐用Tkinter的Text组件替代Label,它支持富文本格式,可以为不同位置的字符添加样式标签。

修改后的完整代码

from random_word import RandomWords
from tkinter import *

# 生成随机单词列表
words = []
r = RandomWords()
for _ in range(100):
    word = r.get_random_word()
    if word:  # 避免生成None值
        words.append(word)

# 初始化主窗口
win = Tk()
window_height = 900
window_width = 1200
screen_width = win.winfo_screenwidth()
screen_height = win.winfo_screenheight()
x_cordinate = int((screen_width/2) - (window_width/2))
y_cordinate = int((screen_height/2) - (window_height/2))
win.geometry(f"{window_width}x{window_height}+{x_cordinate}+{y_cordinate}")

points = 0
current_index = 0  # 跟踪当前需要输入的字符位置

def timeout_message():
    popup = Toplevel(win)
    popup.title("Timeout")
    popup.geometry(f"300x100+{x_cordinate+450}+{y_cordinate+400}")
    Label(popup, text="Time's up!", font=("Arial", 20)).pack()
    popup.focus_set()

def start():
    global current_index
    start_button.pack_forget()
    current_index = 0  # 重置输入位置

    # 创建Text组件显示目标文本
    text_display = Text(win, font=("Arial", 30), wrap=WORD, state=DISABLED)
    text_display.pack(pady=20, padx=20, fill=BOTH, expand=True)
    
    # 插入目标文本并设置默认样式
    target_text = ' '.join(words)
    text_display.config(state=NORMAL)
    text_display.insert(END, target_text)
    text_display.config(state=DISABLED)

    # 定义样式标签
    text_display.tag_config("correct", foreground="green")
    text_display.tag_config("incorrect", foreground="red")

    win.after(30000, timeout_message)

    def check_char(event):
        global current_index, points
        target_text = ' '.join(words)
        
        # 超出文本长度或不可打印字符直接返回
        if current_index >= len(target_text) or not event.char.strip() and event.char != ' ':
            return
        
        input_char = event.char
        target_char = target_text[current_index]

        # 匹配判断并设置颜色
        text_display.config(state=NORMAL)
        if input_char == target_char:
            text_display.tag_add("correct", f"1.{current_index}", f"1.{current_index+1}")
            points += 1
        else:
            text_display.tag_add("incorrect", f"1.{current_index}", f"1.{current_index+1}")
        text_display.config(state=DISABLED)

        current_index += 1  # 移动到下一个字符位置

    # 绑定所有按键事件
    win.bind("<Key>", check_char)

# 创建开始按钮
start_button = Button(win, text="Start", font=("Arial",30), command=start)
start_button.pack(pady=50)

win.mainloop()

关键改动说明

  • 替换Label为Text组件:Text支持通过tag为指定范围的字符设置样式,完美解决单个字符颜色修改的需求
  • 跟踪输入位置:用current_index变量记录当前需要输入的字符位置,每次按键后自动更新
  • 样式标签配置:通过tag_config定义"correct"(绿色)和"incorrect"(红色)两种样式,匹配后用tag_add应用到对应字符
  • 优化事件绑定:只绑定一次<Key>事件,避免循环绑定导致的事件覆盖问题
  • 处理边界情况:判断输入是否超出文本长度,过滤无效按键

内容的提问来源于stack exchange,提问作者Patryk Opiela

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 18:06:05