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

运行Kivy kivy_garden.graph实时图表代码报错Python已停止工作如何解决

问题排查与修复方案

错误根因

  • 你将Graph、MeshLinePlot控件实例定义为App的类属性,Kivy控件需要在App实例初始化完成、渲染上下文就绪后再创建,类加载阶段提前初始化控件会触发底层C++层面的内存访问违规,对应你遇到的错误码0xC0000005。
  • 创建MeshLinePlot实例后没有将其添加到Graph控件的渲染队列中,更新无绑定的plot属性会触发空指针访问错误。
  • 冗余的update_xaxis定时任务重复设置固定的坐标轴范围,额外增加了渲染线程的负担。

修复后的可运行代码

from math import sin
from kivy_garden.graph import Graph, MeshLinePlot
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.clock import Clock

class MyApp(App):
    def build(self):
        # 控件初始化挪到build方法中,使用实例属性存储
        self.plot = MeshLinePlot(color=[1, 0, 0, 1])
        self.graph = Graph(xlabel='X', ylabel='Y', x_ticks_minor=5,
            x_ticks_major=25, y_ticks_major=1,
            y_grid_label=False, x_grid_label=False, padding=5,
            x_grid=False, y_grid=False, xmin=0, xmax=100, ymin=-1, ymax=1)
        # 将曲线添加到图表中
        self.graph.add_plot(self.plot)

        box = BoxLayout()
        box.add_widget(self.graph)
        Clock.schedule_interval(self.update_points, 1/60.)

        return box

    def update_points(self, *args):
        self.plot.points = [(x, sin(x / 10.)) for x in range(0, 101)]

if __name__ == "__main__":
    MyApp().run()

验证说明

运行修复后的代码即可正常显示红色正弦曲线,没有崩溃问题。如果需要做真正的滚动实时图表,只需要修改update_points里的逻辑,同步调整graph的xmin和xmax即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 06:06:03