You need to enable JavaScript to run this app. Tkinter键盘模拟器dif()函数如何根据复杂度动态调整k值生成测试文本
优惠活动
大模型
产品
解决方案
定价
更多

Tkinter键盘模拟器dif()函数如何根据复杂度动态调整k值生成测试文本

代码修改方案

现有问题

你当前的代码存在两个核心问题导致无法动态调整测试文本长度:

  1. dif() 函数没有定义形参接收传入的k值,也没有关联command1()中生成的k参数
  2. 读取词库生成测试文本、创建Text组件的逻辑都写在dif()函数外部,属于全局初始化逻辑,只会执行一次,不会跟随复杂度选择重新生成文本

具体修改步骤

1. 重构dif()函数

为dif()添加k形参,将测试文本生成、Text组件更新逻辑全部移入函数内部,同时做重复创建Text组件的兼容处理。

2. 修改command1()调用逻辑

调用dif()时将对应复杂度的k值作为参数传入。

修改后完整代码

调整后的dif()函数

def dif(k):
    global start_time, test_text, text_widget
    message.pack()
    start_time = time.time()

    # 词库读取与测试文本生成逻辑移入函数内部
    with open("words.txt", "r") as words:
        test_words1 = choices(list(words), k=k)

    len_word_list = [len(word.strip()) for word in test_words1]
    index_nostrip1 = 6
    end_of_line1 = 0
    final_word_list1 = []
    lines_list1 = []
    line1 = ""

    for i in range(len(test_words1)):
        if end_of_line1 == index_nostrip1 - 1:
            final_word_list1.append(test_words1[i])
            line1 += test_words1[i].strip()
            lines_list1.append(line1)
            line1 = ""
            end_of_line1 = 0
        else:
            final_word_list1.append(test_words1[i].strip())
            line1 += f"{test_words1[i].strip()} "
            end_of_line1 += 1

    test_text = " ".join(final_word_list1)

    # Text组件兼容处理:首次调用创建,后续调用复用组件更新内容
    if 'text_widget' not in globals():
        text_widget = Text(root, height=10, width=100,
                        padx=20, pady=20, font=("Arial ", 16))
        text_widget.tag_config("correct", background="green", foreground="white")
        text_widget.tag_config("wrong", background="red", foreground="white")
        text_widget.bind("<KeyPress>", key_type)
    else:
        text_widget.configure(state="normal")
        text_widget.delete(1.0, END)
    
    text_widget.insert(END, test_text)
    text_widget.configure(state="disabled")
    text_widget.pack()
    text_widget.focus()

调整后的command1()函数

def command1():
    if var.get() == 0:
        k = 10
    elif var.get() == 1:
        k = 15
    elif var.get() == 2:
        k = 20
    # 传入k参数调用dif
    dif(k)
    root.deiconify()  
    top.destroy()

额外注意

请删除你原来写在dif()函数外部的全局Text组件创建、全局测试文本生成相关代码,避免逻辑冲突。

内容的提问来源于stack exchange,提问作者Eugene Saitamovich

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 15:33:00