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

如何用CustomTkinter OptionMenu指定打字测试的文本行?

打字速度测试程序OptionMenu功能修正方案

原代码里的问题主要有这几个:

  • lesson_option函数定义缺了def关键字,直接导致语法错误
  • load_text里调用lesson_option()时没传参数,触发TypeError(这个函数本来需要接收选中的选项值)
  • 没正确用optionbox.get()获取当前选中的选项,反而绕了个弯用函数返回值,逻辑走不通

下面是修正后的完整代码,直接能用:

import customtkinter as ctk
import random

# 初始化主窗口
root = ctk.CTk()
root.title("打字速度测试")

# 选项菜单的选项对应txt文件的行号,可根据实际行数调整
values = ["1", "2", "3"] 
optionbox = ctk.CTkOptionMenu(master=root, values=values)
optionbox.grid(row=0, column=0, columnspan=1, pady=10, padx=20, sticky="w")
optionbox.set("1")  # 默认选中第1行

def load_text():
    with open("filename.txt", "r") as f:
        lines = f.readlines()
        # 获取当前选中的行号,转成索引(行号减1)
        selected_idx = int(optionbox.get()) - 1
        # 防止选的行号超出文件实际行数,搞个兜底逻辑
        if 0 <= selected_idx < len(lines):
            return lines[selected_idx].strip()
        else:
            return random.choice(lines).strip()

def resetWritingLabels():    
    # 获取选中行对应的测试文本
    text = load_text()
    # 这里写你的后续处理逻辑,比如把文本显示到界面上
    print("当前测试文本:", text)

# 加个测试按钮,点一下就能看到效果
test_btn = ctk.CTkButton(root, text="重置测试文本", command=resetWritingLabels)
test_btn.grid(row=1, column=0, pady=10)

root.mainloop()

如果之后要给选项菜单加选中后的额外逻辑(比如打印提示),可以保留lesson_option函数,调整成这样:

def lesson_option(choice):
    # 这里加选中后的自定义逻辑,比如提示用户选了哪一行
    print(f"已切换到第{choice}行测试文本")
    return int(choice) - 1

# 初始化OptionMenu时绑定这个command
optionbox = ctk.CTkOptionMenu(master=root, values=values, command=lesson_option)

def load_text():
    with open("filename.txt", "r") as f:
        lines = f.readlines()
        selected_choice = optionbox.get()
        selected_idx = lesson_option(selected_choice)
        if 0 <= selected_idx < len(lines):
            return lines[selected_idx].strip()
        else:
            return random.choice(lines).strip()

之前用optionbox.get()没得到理想结果,大概率是调用时机不对——比如在窗口还没初始化完就调用,或者没在需要更新文本的时候重新获取值,现在每次调用load_text都会实时获取最新的选中值,就没问题了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 13:45:31