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

如何在Tkinter中使用Matplotlib实现双数据源实时折线图绘制

问题根因

你的代码仅完成了Input_values.txt的数据解析,Output.txt读取拆分到dataList1后,没有对应的遍历解析逻辑,xList1、yList1始终是空数组,所以第二条折线无法渲染。

修正方案

你需要补充dataList1的遍历解析逻辑,同时建议用with上下文管理器操作文件,避免文件句柄泄漏,也可以增加简单的异常捕获避免单条数据格式错误导致程序崩溃。

修正后的完整代码如下:

from matplotlib import style, animation
import matplotlib.pyplot as plt
# 这里补充你自己的其他依赖导入,比如tkinter相关、Potmeter类的定义

LARGE_FONT= ("Verdana", 12)
style.use("ggplot")

f = plt.Figure(figsize=(6,4), dpi=100)
a = f.add_subplot(111)

def animate(i):
    # 解析输入文件
    xList = []
    yList = []
    with open("Input_values.txt","r") as f_in:
        pullData = f_in.read()
        dataList = pullData.split('\n')
        for eachLine in dataList:
            eachLine = eachLine.strip()
            if len(eachLine) > 1:
                try:
                    x, y = eachLine.split(',')
                    xList.append(float(x))
                    yList.append(float(y))
                except:
                    continue

    # 补充输出文件的解析逻辑
    xList1 = []
    yList1 = []
    with open("Output.txt","r") as f_out:
        pullData1 = f_out.read()
        dataList1 = pullData1.split('\n')
        for eachLine in dataList1:
            eachLine = eachLine.strip()
            if len(eachLine) > 1:
                try:
                    x, y = eachLine.split(',')
                    xList1.append(float(x))
                    yList1.append(float(y))
                except:
                    continue
   
    a.clear()
    a.plot(xList, yList, label="输入电压")
    a.plot(xList1, yList1, label="输出电压")
    a.legend() # 增加图例区分两条线
    
    title = "Potmeter"
    a.set_title(title)
    a.set_xlabel('Time')
    a.set_ylabel('Voltage')
    
    a.set_ylim(0,3)      

app = Potmeter()
ani = animation.FuncAnimation(f, animate, interval=100)
app.mainloop()

额外注意事项

  • 如果两个文件的时间戳条数不一致,绘制时会自动截断到较短的数组长度,建议你写文件的逻辑保证两个文件同时写入相同时间戳的记录,避免折线错位
  • 运行程序时要保证两个txt文件和代码在同一目录下,且程序有文件读取权限

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 05:54:04