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

编写反应时间游戏时遭遇'Nonetype is not callable'错误求助

解决反应时间测试游戏的热键错误问题

核心问题分析

你的代码出现两个关键错误:

  1. 热键参数传递错误:keyboard.add_hotkey('enter', stop(playing))是直接执行stop函数并把返回值(原函数无返回值,即None)传给热键,而非传递可调用的函数对象,这直接触发了Nonetype错误。后续添加return playing后,传入的是布尔值,自然会出现“bool is not callable”的报错。
  2. 全局变量未正确引用:stop函数里的playing是局部变量,修改后不会影响全局的playing状态,导致无法实现停止游戏的逻辑。

修正后的完整代码

import time
import datetime
import random
import keyboard

playing = True

def stop():
    global playing
    playing = False

input("Press enter when you're ready to test your reaction time!")
print("Press enter when you see the cat!")

time.sleep(1)

# 传递函数对象而非执行结果
keyboard.add_hotkey('enter', stop)

time.sleep(random.randint(3, 6))

if playing:
    keyboard.remove_hotkey('enter')
    start = datetime.datetime.now()
    input("Press Enter!!!!")
    end = datetime.datetime.now()
    print(f"Your reaction time: {end - start}")

关键修改说明

  • 重构stop函数:去掉多余参数,用global关键字声明要修改全局的playing变量,确保函数能正确改变游戏状态。
  • 修正热键注册:keyboard.add_hotkey('enter', stop)直接传递函数本身,让热键触发时能调用该函数,避免传入非可调用对象的错误。
  • 优化输出格式:用f-string让反应时间的输出更直观(可选优化)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 18:03:16