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

Python三角函数计算器:按Enter键无法触发计算函数问题求助

问题分析与解决方案

核心问题

你的代码存在三个关键问题:

  1. input() 本身会在用户第一次按下Enter时就读取输入值,后续绑定的Enter热键只会反复使用这个初始值,无法响应新的输入
  2. 程序执行到 keyboard.add_hotkey 后就直接退出,没有保持运行状态监听热键;空 while True 循环缺少事件处理逻辑,导致CPU占用过高出现卡顿
  3. 错误使用 keyboard 库——控制台场景下,input() 原生支持按Enter提交输入,无需额外绑定全局热键

修复后的代码

import math

def operation(val1):
    try:
        # 解析输入的三角函数表达式
        trig_func, deg_value = val1.split('(')
        deg_value = deg_value.strip(')')
        deg_value = float(deg_value)
        radians_value = math.radians(deg_value)

        # 映射三角函数与对应计算函数
        trig_functions = {
            'sin': math.sin,
            'cos': math.cos,
            'tan': math.tan,
            'arcsin': math.asin,
            'arccos': math.acos,
            'arctan': math.atan
        }

        # 执行计算并输出结果
        if trig_func in trig_functions:
            result = trig_functions[trig_func](radians_value)
            print(f"The result of {trig_func}({deg_value}) is: {result}")
        else:
            print("Invalid trigonometric function. Please use sin, cos, tan, arcsin, arccos, or arctan.")
    except ValueError:
        print("Invalid format. Please follow: trig(deg)")

print('Follow format: trig(deg)')
# 循环接收输入,按Enter直接触发计算
while True:
    val1 = input("Enter: ")
    operation(val1)

关键改进点

  • 移除了不必要的 keyboard 和 cmath 库
  • 加入异常处理,避免输入格式错误导致程序崩溃
  • 使用 while True 循环实现持续输入,每次用户按下Enter提交输入后,直接调用 operation() 处理计算,完全符合你的需求
  • 解决了空循环导致的卡顿问题,循环内通过 input() 阻塞等待用户输入,不会占用过多CPU资源

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 13:49:55