Python三角函数计算器:按Enter键无法触发计算函数问题求助
问题分析与解决方案
核心问题
你的代码存在三个关键问题:
input()本身会在用户第一次按下Enter时就读取输入值,后续绑定的Enter热键只会反复使用这个初始值,无法响应新的输入- 程序执行到
keyboard.add_hotkey后就直接退出,没有保持运行状态监听热键;空while True循环缺少事件处理逻辑,导致CPU占用过高出现卡顿 - 错误使用
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
相关产品推荐
相关产品推荐

