如何避免按键重复触发?Python动画控制问题求助
解决按键重复触发与动画启停问题
问题根源
update()函数会在每一帧执行,短按h键时,连续多帧都会检测到keyboard.h为True,导致start状态反复切换,动画逻辑彻底混乱。
解决方案
1. 改用按键边缘触发(仅在按下瞬间响应)
不要直接检测keyboard.h的持续状态,而是只响应按键从松开到按下的瞬间。通过记录上一帧的按键状态实现:
# 在update()函数外部定义变量,记录上一帧h键的状态 last_h_pressed = False def update(): global start, last_h_pressed current_h_pressed = keyboard.h # 仅当当前帧按下h键、且上一帧未按下时,才触发状态切换 if current_h_pressed and not last_h_pressed: if not start: start = True print("hello?") dotty_move() else: start = False print("bye") # 停止正在运行的动画(根据你使用的库调整,比如调用动画对象的stop/cancel方法) # 更新上一帧的按键状态 last_h_pressed = current_h_pressed dot1.pos = x, y dot2.pos = xi, yi
2. 修复动画循环的递归调用问题
当前代码里on_finished直接写了dot_move(),会导致函数立即执行而非动画结束后触发,改成传递函数引用即可:
def dotty_move(): global speed, speedi, start if start == True: # 注意:on_finished传函数名,不要加括号 animate(dot1, duration = speedi, pos = (xi, 0), on_finished = dot_move) animate(dot2, duration = speed, pos = (x, 0), on_finished = dot_move) def dot_move(): global speed, speedi, start, x, y, xi, yi, dot1 if start == True: animate(dot1, pos=(0, 425), on_finished = dotty_move) print("test") animate(dot2, duration = speed, pos = (x, 425), on_finished = dotty_move)
3. 补充动画停止逻辑
当start设为False时,需要主动终止正在运行的动画,不同库的实现方式不同,举两个常见例子:
- 若使用Kivy的
Animation:# 全局保存动画对象 dot1_anim = None dot2_anim = None def dotty_move(): global dot1_anim, dot2_anim if start == True: dot1_anim = animate(dot1, duration = speedi, pos = (xi, 0), on_finished = dot_move) dot2_anim = animate(dot2, duration = speed, pos = (x, 0), on_finished = dot_move) # 在update()的start=False分支添加 if dot1_anim: dot1_anim.cancel(dot1) if dot2_anim: dot2_anim.cancel(dot2) - 若使用自定义动画循环:在
dotty_move()和dot_move()的开头判断start状态,不满足则直接返回。
最终效果
修改后,短按h键只会触发一次状态切换:第一次按启动动画循环,第二次按停止动画并重置状态,不会再出现反复切换的问题。
内容的提问来源于stack exchange,提问作者Whi_24
相关产品推荐
相关产品推荐

