如何从运行在不同线程中的另一个类更新一个类中的self.variables

时间:2019-06-27 19:38:53

标签: python multithreading class tkinter

我试图在按下按钮时从UI类更新线程中运行的给定类的self.variables(因为我有一个while循环来计算一些工作)。因此,当按下主窗口中的保存按钮时,对设置数据集所做的修改将保存到JSON文件中,并且另一个类中的变量也会更新以反映更改。


import time
import os
from threading import Thread
from tkinter import *
from tkinter import ttk


class MainWindow:  # This is UI element which houses all the settings and vectors to be modified
    def __init__(self, top, settings, vectors):
        self.top = top
        self.top.resizable(0, 0)

        self.settings = settings
        self.vectors = vectors

        self.Btn_4_2 = ttk.Button(top)
        self.Btn_4_2.place(height=25, width=50)
        self.Btn_4_2.configure(text='''Save''')
        self.Btn_4_2.configure(command=self.Btn_4_2_Fun)

    def Btn_4_2_Fun(self):  # this button is used to save the modification to the json file
        database_save(self.settings, self.vectors)
       # Dataset.constructure()  # update the self variables in the Dataset class to reflect the changes made in the UI
        return

class Dataset:

    def __init__(self, settings, vectors):
        self.vec_1 = None
        self.vec_2 = None

        self.constructure(settings, vectors)  # Assign all required variables using this method

        self.core()  # Run the While loop to do the required computation
        return

    def constructure(self, settings, vectors):
        self.vec_1 = settings[0]
        self.vec_2 = vectors[2]
        return

    def core(self):
        while True:
            time.sleep(0.1)
            if self.vec_1 == 6:
                print("problem")
            elif self.vec_2 == 10:
                print("found")
        retrun


def database_read():

    settings = [1,2,3,4,5,6,7,8,9,10]

    vectors = [10,9,8,7,6,5,4,3,2,1]

    return settings, vectors

def database_save(settings, vectors):

    print(settings, vectors)

    return

def main():

    settings, vectors = database_read() # returns the databases stored in a json file

    # UI Declaration
    root = Tk()
    Main = MainWindow(root, settings, vectors)

    #Dataset reader thread
    A_thread = Thread(target=Dataset, args=[settings, vectors])
    A_thread.setDaemon(True)
    A_thread.start()

    # UI Start
    root.mainloop()
    os._exit(1)
    return

main()

我对此问题的可行解决方案是将“构造函数”方法转换为@classmethod并将所需的变量声明为类变量。但是我不确定这是否是一个好的解决方案

0 个答案:

没有答案