求助为什么绘制不了折线图

m0_71347911 2024-07-15 20:41:19
# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'ttt.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again.  Do not edit this file unless you know what you are doing.


from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(761, 440)
        self.widget = QtWidgets.QWidget(Form)
        self.widget.setGeometry(QtCore.QRect(10, 10, 441, 291))
        self.widget.setObjectName("widget")
        self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.widget)
        self.verticalLayout_2.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.verticalLayout = QtWidgets.QVBoxLayout()
        self.verticalLayout.setObjectName("verticalLayout")
        self.verticalLayout_2.addLayout(self.verticalLayout)
        self.pushButton = QtWidgets.QPushButton(Form)
        self.pushButton.setGeometry(QtCore.QRect(40, 370, 201, 31))
        self.pushButton.setObjectName("pushButton")
        self.lineEdit = QtWidgets.QLineEdit(Form)
        self.lineEdit.setGeometry(QtCore.QRect(100, 330, 121, 21))
        self.lineEdit.setObjectName("lineEdit")
        self.label = QtWidgets.QLabel(Form)
        self.label.setGeometry(QtCore.QRect(50, 330, 51, 16))
        self.label.setObjectName("label")
        self.label_2 = QtWidgets.QLabel(Form)
        self.label_2.setGeometry(QtCore.QRect(230, 330, 54, 12))
        self.label_2.setObjectName("label_2")
        self.label_3 = QtWidgets.QLabel(Form)
        self.label_3.setGeometry(QtCore.QRect(480, 180, 201, 201))
        self.label_3.setText("")
        self.label_3.setPixmap(QtGui.QPixmap("../图像材料/black_light.jpg"))
        self.label_3.setObjectName("label_3")

        self.label_4 = QtWidgets.QLabel(Form)
        self.label_4.setGeometry(QtCore.QRect(480, 180, 201, 201))
        self.label_4.setText("")
        self.label_4.setPixmap(QtGui.QPixmap("../图像材料/green_light.jpg"))
        self.label_4.setObjectName("label_4")
        self.label_4.hide()

        self.label_5 = QtWidgets.QLabel(Form)
        self.label_5.setGeometry(QtCore.QRect(480, 180, 201, 201))
        self.label_5.setText("")
        self.label_5.setPixmap(QtGui.QPixmap("../图像材料/red_light.jpg"))
        self.label_5.setObjectName("label_5")
        self.label_5.hide()

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
        self.pushButton.setText(_translate("Form", "导出Excle"))
        self.label.setText(_translate("Form", "距离:"))
        self.label_2.setText(_translate("Form", "cm"))

 

# from PyQt5.QtGui import QPixmap
# from threading import Thread
import sys
import time
from collections import deque
import requests
import matplotlib.pyplot as plt
import xlwt
from PyQt5.QtCore import QTimer
from matplotlib import animation
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FC
from matplotlib.figure import Figure

import tui
from PyQt5.QtWidgets import *


class windos(QWidget):

    def __init__(self):
        super(windos, self).__init__()
        self.ui = tui.Ui_Form()
        self.ui.setupUi(self)
        # self.ui.pushButton.clicked.connect(self.exice)
        self.AccessToken()

        self.x = []
        self.y = []

        self.fig, self.axs = plt.subplots(nrows=1, ncols=1, figsize=(10, 5))
        self.canvas = FC(self.fig)
        self.ui.verticalLayout.addWidget(self.canvas)

        self.timer = QTimer(self)
        self.timer.timeout.connect(self.init_ui)
        self.timer.start(1000)  # 每秒更新一次

    def AccessToken(self):
        url = "http://api.nlecloud.com/users/login"
        user = {
            'Account': '1xxxxxxx7',
            'Password': '1xxxx6'
        }
        token = {'AccessToken': requests.post(url=url, data=user).json()['ResultObj']['AccessToken']}
        return token

    def csb_cgq(self):
        while 1:
            self.csb_shuju = requests.get(url=f"http://api.nlecloud.com/devices/1049542/sensors/m_hum",
                                          params=self.AccessToken()).json()['ResultObj']['Value']
            self.csb_shijian = requests.get(url=f"http://api.nlecloud.com/devices/1049542/sensors/m_hum",
                                            params=self.AccessToken()).json()['ResultObj']['RecordTime']

            return self.csb_shuju, self.csb_shijian

    def init_ui(self):
        self.shuju, self.shijian = self.csb_cgq()
        print(self.shuju)
        print(self.shijian)
        self.x.append(self.shijian)
        self.y.append(int(self.shuju))
        if len(self.x) > 5:  # 例如,只保留最近5个数据点
            self.x.pop(0)
            self.y.pop(0)
        print(self.x)
        print(self.y)

        self.axs.clear()
        self.axs.plot(self.x, self.y, label='温度', color='blue', marker='o')
        self.axs.set_title('温度')
        self.axs.set_xlabel('时间')
        self.axs.set_ylabel('温度')
        self.axs.legend()

        # plt.tight_layout()
        # ani = animation.FuncAnimation(self.fig, self.init_ui, interval=1000)  # 每秒更新一次
        # plt.rcParams['font.sans-serif'] = ['SimHei']
        # plt.show()

    def exice(self):
        self.wb = xlwt.Workbook('utf-8')
        self.ws = self.wb.add_sheet('book')
        self.ws.write(0, 0, '数据')
        self.ws.write(0, 1, '时间')
        self.row = 0
        for i in range(20):
            self.row += 1
            self.ws.write(self.row, 0, self.csb_shuju)
            self.ws.write(self.row, 1, self.csb_shijian)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ui = windos()
    ui.show()
    sys.exit(app.exec_())

 

 

 

 

 

 

...全文
247 1 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
Slingerspir 2024-07-19
  • 打赏
  • 举报
回复

在您提供的代码中,您正在尝试使用PyQt5和matplotlib在PyQt5应用程序中绘制折线图。根据您提供的代码和问题描述,这里有几个可能的原因和建议来解决无法绘制折线图的问题:

确保matplotlib绘图库正确安装:您需要确保matplotlib库已经正确安装在您的环境中。您可以使用pip install matplotlib来安装。

检查数据更新逻辑:在init_ui方法中,您从API获取数据并更新图表。请确保数据获取逻辑是正确的,并且数据被正确地添加到self.x和self.y列表中。

检查定时器逻辑:您使用了QTimer来定期更新UI。确保定时器被正确启动,并且init_ui方法被定时调用。

检查图表绘制逻辑:在init_ui方法中,您清除了当前的轴并绘制了新的数据。请确保在添加数据到图表之前,数据列表self.x和self.y不为空。

检查API响应:请确保API调用成功,并且返回了预期的数据格式。您可以打印API响应来检查数据是否正确。

检查布局:确保FigureCanvasQTAgg(即matplotlib的画布)被正确添加到PyQt5的布局中。在您的代码中,您使用了self.ui.verticalLayout.addWidget(self.canvas)来添加画布,确保这个布局是可见的,并且有足够的空间来显示图表。

检查线程使用:如果您在另一个线程中更新UI,确保您使用信号和槽来安全地更新UI。在PyQt5中,所有UI更新都应该在主线程中完成。

检查错误处理:添加错误处理逻辑来捕获和处理可能出现的任何异常,例如网络请求失败或数据解析错误。

检查图像路径:确保图像路径是正确的,并且图像文件存在于指定的位置。

运行环境:确保您的运行环境支持图形界面,并且所有依赖库都与您的Python版本兼容。

如果上述检查都没有问题,但问题仍然存在,您可能需要进一步调试代码,查看是否有其他潜在的问题。您可以在关键位置添加打印语句来跟踪程序的执行流程和变量的状态,或者使用Python的调试工具来逐步执行代码。

6,234

社区成员

发帖
与我相关
我的任务
社区描述
人生苦短,我用python
社区管理员
  • Python 学习者
  • 嗨学编程
  • 松鼠爱吃饼干
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

欢迎来到Python学习者们的社区,

 

本社区分享你需要的文章、问题解答、技术互助、学习资源、面试系列等等

 

欢迎你的加入,祝你学有所成~

试试用AI创作助手写篇文章吧