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

Python实现每秒调用函数:Viewer类单次按Z键自动更新point_info

解决方案:实现单次按键后每秒自动更新point_info

Got it, let's tweak your Viewer class so you only need to press Z once to start updating point_info automatically every second. Here's the modified code with explanations:

import pyglet

class Viewer: 
    def __init__(self, width, height, arm_info, point_info, point_l): 
        self.list_x = [1,2,3,4] 
        self.list_y = [5,6,7,8] 
        self.i = 0 
        self.arm_info = arm_info 
        self.point_info = point_info 
        self.update_scheduled = False  # 标记自动更新是否已启动

    def update_point_info(self, dt):
        # 更新point_info为当前索引对应的坐标
        self.point_info[:] = [self.list_x[self.i], self.list_y[self.i]] 
        self.i += 1
        # 当索引超出列表长度时重置,实现循环更新
        if self.i >= len(self.list_x):
            self.i = 0

    def on_key_press(self,symbol,modifiers): 
        if symbol == pyglet.window.key.Z and not self.update_scheduled:
            # 调度每秒执行一次update_point_info函数
            pyglet.clock.schedule_interval(self.update_point_info, 1.0)
            self.update_scheduled = True
            print("自动更新已启动!再次按Z不会重复触发。")

关键修改说明:

  • self.update_scheduled 标记:用来避免多次按Z键重复添加定时任务,防止更新频率意外变快。
  • update_point_info 独立方法:把更新逻辑抽成单独方法,既负责修改point_info,还处理了索引重置——遍历完列表后会从头开始循环,避免索引越界报错。
  • pyglet.clock.schedule_interval:这是Pyglet自带的定时调度工具,第一个参数是要执行的函数(需要接受dt参数,Pyglet会自动传入上次调用到现在的时间差),第二个参数是调用间隔(单位为秒,这里设1.0就是每秒一次)。
  • 修改后的按键逻辑:只有当Z键按下且自动更新未启动时,才会开启定时任务,避免误操作重复触发。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:37:48