【问题标题】:How to refresh, update or disconnect signal in PyQt5?如何在 PyQt5 中刷新、更新或断开信号?
【发布时间】:2017-08-23 04:38:04
【问题描述】:

我将一个按钮连接到一个绘制图表的方法。它按预期工作,但是当我关闭图形窗口并单击按钮尝试再次显示绘图时,没有任何反应。

我尝试了refreshupdatedisconnect,但找不到解决方案。我是 PyQt 的新手。

这是我所拥有的:

import plot
self.btn.clicked.connect(self.showPlot)
def showPlot(self):
        plot.plt.show()

代码示例

绘图模块: plot.py

import numpy as np
import matplotlib.pyplot as plt

N = 5
first_means = (20, 35, 30, 35, 27)
first_std = (2, 3, 4, 1, 2)

ind = np.arange(N)
width = 0.35     

fig, ax = plt.subplots()
rects1 = ax.bar(ind, first_means, width, color='r', yerr=first_std)

second_means = (25, 32, 34, 20, 25)
second_std = (3, 5, 2, 3, 3)
rects2 = ax.bar(ind + width, second_means, width, color='y', yerr=second_std)

PyQt5 模块:

import sys
from PyQt5.QtWidgets import (QWidget, QPushButton, QApplication)
import plot

class Example(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):      

        self.btn = QPushButton('Show Plot', self)
        self.btn.move(20, 20)
        self.btn.clicked.connect(self.showPlot)

        self.setGeometry(300, 300, 290, 150)
        self.setWindowTitle('Show Plot')
        self.show()

    def showPlot(self):
        plot.plt.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

【问题讨论】:

  • 请提供MCVE。您发布的代码不完整,没有说明问题。您无需更改任何内容即可使信号多次工作
  • @user3419537 感谢您的评论。我认为我最初的问题符合 MCVE,因为它描述了实际问题。但是,你是对的,一些额外的示例代码可能会有所帮助。因此,我编辑了我的问题并发布了一个示例。

标签: python python-3.x matplotlib pyqt pyqt5


【解决方案1】:

当您关闭窗口时,它会消除 matplotlib 的应用,除了在另一个文件中包含脚本不是一个好习惯之外,建议只包含函数、类和/或定义,因此我建议您将项目重组为以下:

plot.py

import numpy as np
import matplotlib.pyplot as plt

def customplot():
    N = 5
    first_means = (20, 35, 30, 35, 27)
    first_std = (2, 3, 4, 1, 2)

    ind = np.arange(N)
    width = 0.35     

    fig, ax = plt.subplots()
    rects1 = ax.bar(ind, first_means, width, color='r', yerr=first_std)

    second_means = (25, 32, 34, 20, 25)
    second_std = (3, 5, 2, 3, 3)
    rects2 = ax.bar(ind + width, second_means, width, color='y', yerr=second_std)
    plt.show()

ma​​in.py

import sys
from PyQt5.QtWidgets import (QWidget, QPushButton, QApplication)
import plot

class Example(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):      
        self.btn = QPushButton('Show Plot', self)
        self.btn.move(20, 20)
        self.btn.clicked.connect(self.showPlot)

        self.setGeometry(300, 300, 290, 150)
        self.setWindowTitle('Show Plot')
        self.show()

    def showPlot(self):
        plot.customplot()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

注意:在我的情况下,你的代码永远不会工作,因为窗口总是被阻塞,而不是我建议的实现效果最佳。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-09
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-03
    相关资源
    最近更新 更多