繁体   English   中英

Python threading - 在另一个 class 中更改变量值

[英]Python threading - Change variable value in another class

我正在寻找一种方法来更改不同线程中类之间的变量。 由于我最近有一个关于线程的问题,我想再次使用该示例代码来解决这个问题。

主文件:

#PROGRAM/SCRIPT
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication
import sys
import GUI
import datetime
import pyqtgraph
import time
plotsize = 20


class Worker2(QtCore.QThread):
    def __init__(self):
        print("Thread2 has been started")
        
    def run(self):
        #now get access to variable of class Worker
        
# =============================================================================
# Threading for not freezing the GUI while running
# =============================================================================
class Worker(QtCore.QThread):
    progress = QtCore.pyqtSignal(int)
    finished = QtCore.pyqtSignal()
    widgetplot = QtCore.pyqtSignal(list, list)

    def __init__(self, plot_time, plot_value):
        print("Thread has been started")
        QtCore.QThread.__init__(self, objectName='WorkerThread')
        self.plot_time = plot_time
        self.plot_value = plot_value

    def run(self):
        #now get access to variable of Worker2
        _count = 0

        _start_time = datetime.datetime.now()
        while 0 <= _count < 100:
            # Use local variable!
            _count_prev = _count
            QtCore.QThread.usleep(10000)
            _diff = datetime.datetime.now() - _start_time
            _count = int((_diff.total_seconds() * 10))
            if(_count != _count_prev):
                print(_count)
                x = self.plot_time[:_count]
                y = self.plot_value[:_count]
                self.widgetplot.emit(x, y)


class my_class(QtWidgets.QMainWindow, GUI.Ui_MainWindow):
    def __init__(self, parent=None):
        super(my_class, self).__init__(parent)
        self.setupUi(self)
        
        self.WidgetPlot.setXRange(0, 105, padding=0)
        self.WidgetPlot.setYRange(0, 105, padding=0)

        self.second_line = pyqtgraph.PlotDataItem(pen=pyqtgraph.mkPen('w', width=plotsize*2))
        
        self.plot_time = []
        self.plot_value = []

        self.worker_thread = Worker(self.plot_time, self.plot_value)

        self.worker_thread.widgetplot.connect(self.update_second_line_plot)

        self.worker_thread2 = Worker2()

        self.pushButton.clicked.connect(self.my_function)

        self.WidgetPlot.setMouseEnabled(x=False, y=False)
        font=QtGui.QFont()
        font.setPixelSize(20)
        font.setBold(True)
        self.WidgetPlot.getAxis("bottom").setTickFont(font)
        self.WidgetPlot.getAxis("left").setTickFont(font)


    def my_function(self):
        _l = list(range(100))
        self.plot_time.extend(_l)
        self.plot_value.extend(_l)

        self.start()
        
    def update_second_line_plot(self, plot_time, plot_value):
        self.second_line.setData(plot_time, plot_value)


    def start(self):
        self.WidgetPlot.plot(self.plot_time, self.plot_value, pen=pyqtgraph.mkPen('r', width=plotsize))

        self.WidgetPlot.addItem(self.second_line)
    
        self.worker_thread.start() 
        self.worker_thread2.start()
    


def main():
    app = QApplication(sys.argv)
    form = my_class()
    form.show()
    app.exec_()
    
    
if __name__ == '__main__':
    main()

界面:

#GUI.py
from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(739, 532)
        MainWindow.setStyleSheet("")
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.WidgetPlot = PlotWidget(self.centralwidget)
        self.WidgetPlot.setGeometry(QtCore.QRect(100, 40, 541, 341))
        self.WidgetPlot.setObjectName("WidgetPlot")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(330, 420, 93, 28))
        self.pushButton.setObjectName("pushButton")
        MainWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

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

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "Main Window"))
        self.pushButton.setText(_translate("MainWindow", "Start"))

from pyqtgraph import PlotWidget

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

我想从 class Worker 更改 class Worker2 中的变量,反之亦然。

提前谢谢了!

安德鲁

但对于其他 class 没有办法调用/更改变量...

Python中的成员变量*默认是public的。**假设你有

class P:
    def __init__(self):
        self.q = "whatever"
    def printit(self):
        print(self.q) 

您可以在 repl 中执行此操作:

>>> p = P()
p = P()
>>> p.printit()
p.printit()
whatever
>>> p.q
p.q
'whatever'
>>> p.q = 'new value'
p.q = 'new value'
>>> p.printit()
p.printit()
new value
>>> p.q
p.q
'new value'

您可以在引用属于class P的 object 的 Python 代码中的任何位置执行相同操作。


* “属性?” “田地?” 我编写了很多 Python 程序,这些程序是我从事的项目的辅助程序——主要供我自己使用。 我和其他 Python 程序员谈得不多,我也不太懂行话。

** 有关“公共”与“私有”的更多信息,请参阅https://towardsdatascience.com/private-protected-attributes-in-python-demystified-once-and-for-all-9456d4e56414

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM